/**
 * Usage repository — cloud-agnostic via @bytelyst/datastore.
 */

import { getCollection } from '../../lib/datastore.js';
import type { UsageDoc, MonthlyUsage } from './types.js';

function collection() {
  return getCollection<UsageDoc>('usage_daily', '/userId');
}

export async function getByDate(userId: string, date: string): Promise<UsageDoc | null> {
  const id = `usg_${date}_${userId}`;
  try {
    return await collection().findById(id, userId);
  } catch {
    return null;
  }
}

export async function list(
  options: { userId?: string; days?: number; limit?: number; productId?: string } = {}
): Promise<UsageDoc[]> {
  const { userId, days = 30, limit = 100, productId } = options;
  const since = new Date(Date.now() - days * 86400000).toISOString().slice(0, 10);

  // Fetch all matching docs and filter in-memory for $gte on date
  const filter: Record<string, unknown> = { date: { $gte: since } };
  if (productId) filter.productId = productId;
  if (userId) filter.userId = userId;

  return collection().findMany({
    filter: filter as import('@bytelyst/datastore').FilterMap,
    sort: { date: -1 },
    limit,
  });
}

export async function upsert(doc: UsageDoc): Promise<UsageDoc> {
  return collection().upsert(doc);
}

export async function getMonthlyUsage(userId: string, productId: string): Promise<MonthlyUsage> {
  const now = new Date();
  const monthStart = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`;

  // Fetch docs for this month and aggregate in-memory
  const docs = await collection().findMany({
    filter: {
      productId,
      userId,
      date: { $gte: monthStart },
    } as import('@bytelyst/datastore').FilterMap,
  });

  let tokens = 0;
  let words = 0;
  let dictations = 0;
  for (const doc of docs) {
    tokens += doc.tokensUsed ?? 0;
    words += doc.words ?? 0;
    dictations += doc.dictations ?? 0;
  }

  return { tokens, words, dictations };
}
