import { queries } from './db';

export function startOfCurrentMonth(): number {
  const d = new Date();
  d.setUTCDate(1);
  d.setUTCHours(0, 0, 0, 0);
  return d.getTime();
}

export function usageCountThisMonth(accountId: string): number {
  return queries.usageCountSince.get(accountId, startOfCurrentMonth())?.c ?? 0;
}

export function usageByDataset(
  accountId: string
): Array<{ dataset: string; count: number }> {
  const rows = queries.usageByDataset.all(accountId, startOfCurrentMonth());
  return rows.map((r: { dataset: string; c: number }) => ({
    dataset: r.dataset,
    count: r.c
  }));
}

export function usageByKey(
  accountId: string
): Array<{ keyId: string; name: string; count: number }> {
  const rows = queries.usageByKey.all(startOfCurrentMonth(), accountId);
  return rows.map((r: { key_id: string; name: string; c: number }) => ({
    keyId: r.key_id,
    name: r.name,
    count: r.c
  }));
}
