import { sql } from "drizzle-orm";
import { schema, type Database } from "@app/database";

function currentMonth(): string {
  const d = new Date();
  return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`;
}

/**
 * Bokför AI-användning utan PII i ai_usage_counters.
 * Används av både scan-processor och UPDATE_USER_MEMORY.
 */
export async function recordAiUsage(
  db: Database,
  userId: string,
  usage: { costUsd: number; inputTokens: number; outputTokens: number; aiScans?: number },
): Promise<void> {
  const microcents = Math.round(usage.costUsd * 100_000_000);
  const month = currentMonth();
  const aiScans = usage.aiScans ?? 0;

  await db
    .insert(schema.aiUsageCounters)
    .values({
      userId,
      month,
      aiScans,
      aiTokensIn: usage.inputTokens,
      aiTokensOut: usage.outputTokens,
      aiCostUsdMicrocents: microcents,
    })
    .onConflictDoUpdate({
      target: [schema.aiUsageCounters.userId, schema.aiUsageCounters.month],
      set: {
        aiScans: sql`${schema.aiUsageCounters.aiScans} + ${aiScans}`,
        aiTokensIn: sql`${schema.aiUsageCounters.aiTokensIn} + ${usage.inputTokens}`,
        aiTokensOut: sql`${schema.aiUsageCounters.aiTokensOut} + ${usage.outputTokens}`,
        aiCostUsdMicrocents: sql`${schema.aiUsageCounters.aiCostUsdMicrocents} + ${microcents}`,
      },
    });
}
