/**
 * KV key layout for the install-funnel worker.
 *
 *   session:<session_id>           — `{ events_seen: number }` (2h TTL)
 *   event:<session_id>:<stage>     — JSON event record (14d TTL)
 *   funnel:weekly:<iso-week>       — aggregate counters (24mo TTL)
 *
 * `session_id` is the random 128-bit hex token generated by the worker.
 * `<iso-week>` is `<year>-W<week>` (e.g. `2026-W21`).
 */

import type { TelemetryStage } from './types.js';

export function sessionKey(sessionId: string): string {
    return `session:${sessionId}`;
}

export function eventKey(sessionId: string, stage: TelemetryStage): string {
    return `event:${sessionId}:${stage}`;
}

export function weeklyAggregateKey(isoWeek: string): string {
    return `funnel:weekly:${isoWeek}`;
}

/** ISO week token (`<year>-W<week>`) for a given timestamp. */
export function isoWeekOf(ts: Date): string {
    const date = new Date(Date.UTC(ts.getUTCFullYear(), ts.getUTCMonth(), ts.getUTCDate()));
    const dayNum = date.getUTCDay() === 0 ? 7 : date.getUTCDay();
    date.setUTCDate(date.getUTCDate() + 4 - dayNum);
    const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
    const weekNum = Math.ceil(((date.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
    return `${date.getUTCFullYear()}-W${String(weekNum).padStart(2, '0')}`;
}
