/**
 * Login events repository — CRUD for auth_login_events container.
 */

import { getCollection } from '../../../lib/datastore.js';
import type { LoginEventDoc } from './types.js';

function eventsCollection() {
  return getCollection<LoginEventDoc>('auth_login_events', '/userId');
}

export async function record(doc: LoginEventDoc): Promise<LoginEventDoc> {
  return eventsCollection().create(doc);
}

export async function listByUser(
  userId: string,
  options?: { limit?: number; result?: string; since?: string }
): Promise<LoginEventDoc[]> {
  const filter: Partial<LoginEventDoc> = { userId };
  if (options?.result) (filter as Record<string, string>).result = options.result;
  const results = await eventsCollection().findMany({
    filter: filter as Record<string, string>,
    sort: { createdAt: -1 },
    limit: options?.limit ?? 50,
  });
  if (options?.since) {
    return results.filter(e => e.createdAt >= options.since!);
  }
  return results;
}

export async function countRecentFailures(userId: string, sinceMs: number): Promise<number> {
  const since = new Date(Date.now() - sinceMs).toISOString();
  const events = await eventsCollection().findMany({
    filter: { userId, result: 'failed' },
    limit: 100,
  });
  return events.filter(e => e.createdAt >= since).length;
}
