import { ValidationError } from "../errors.js";

/**
 * Time basis of the date filter for usage metrics.
 * - activity: messages, tokens and models are filtered by `message_metrics.created_at` (the row
 *   that owns the counters), consistent with analytics_timeseries;
 * - session_updated (legacy default): every metric of the sessions whose `updated_at` falls in the
 *   range, so an old session touched today contributes all its historical tokens.
 * Sessions are always filtered by `sessions.updated_at` and events by `runtime_events.occurred_at`.
 */
export const TIME_BASES = ["activity", "session_updated"] as const;
export type TimeBasis = (typeof TIME_BASES)[number];

export function parseTimeBasis(value: unknown): TimeBasis {
  if (value === undefined) return "session_updated";
  if (typeof value !== "string" || !(TIME_BASES as readonly string[]).includes(value)) {
    throw new ValidationError(`time_basis must be one of: ${TIME_BASES.join(", ")}.`);
  }
  return value as TimeBasis;
}

export function timeSemantics(basis: TimeBasis): Record<string, string> {
  const metricColumn = basis === "activity" ? "message_metrics.created_at" : "sessions.updated_at";
  return {
    sessions: "sessions.updated_at",
    messages: metricColumn,
    tokens: metricColumn,
    models: metricColumn,
    events: "runtime_events.occurred_at"
  };
}
