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

import type { FilterMap } from '@bytelyst/datastore';
import { getCollection } from '../../lib/datastore.js';
import type { AuditDoc, QueryAuditInput } from './types.js';

// Default TTL: 90 days in seconds
const DEFAULT_TTL = 90 * 24 * 60 * 60;

function collection() {
  return getCollection<AuditDoc>('audit_log', '/productId');
}

export async function create(doc: AuditDoc): Promise<AuditDoc> {
  return collection().create({
    ...doc,
    ttl: doc.ttl ?? DEFAULT_TTL,
  });
}

export async function query(input: QueryAuditInput, productId: string): Promise<AuditDoc[]> {
  const { userId, action, category, days, limit, offset } = input;
  const since = new Date(Date.now() - days * 86400000).toISOString();

  const filter: FilterMap = {
    productId,
    createdAt: { $gte: since },
  };
  if (userId) filter.userId = userId;
  if (action) filter.action = action;
  if (category) filter.category = category;

  const results = await collection().findMany({
    filter,
    sort: { createdAt: -1 },
    limit: limit + offset,
  });
  return results.slice(offset);
}

export async function getStats(days = 30, productId?: string): Promise<Record<string, number>> {
  const since = new Date(Date.now() - days * 86400000).toISOString();
  // Fetch docs and aggregate in-memory
  const docs = await collection().findMany({
    filter: {
      productId: productId ?? '',
      createdAt: { $gte: since },
    },
  });

  const stats: Record<string, number> = {};
  for (const doc of docs) {
    stats[doc.action] = (stats[doc.action] ?? 0) + 1;
  }
  return stats;
}
