import type { FastifyInstance } from 'fastify';
import type { AuditLogService } from '../services/audit-log.service.js';

interface AuditLogQuery {
  userId?: string;
  action?: string;
  resource?: string;
  resourceId?: string;
  since?: string;
  until?: string;
  limit?: string;
  offset?: string;
}

export function registerAuditLogRoutes(app: FastifyInstance, service: AuditLogService): void {
  app.get<{ Querystring: AuditLogQuery }>('/api/v1/audit-logs', async (request) => {
    const q = request.query;
    const params: Record<string, unknown> = {};
    if (q.userId !== undefined) params.userId = q.userId;
    if (q.action !== undefined) params.action = q.action;
    if (q.resource !== undefined) params.resource = q.resource;
    if (q.resourceId !== undefined) params.resourceId = q.resourceId;
    if (q.since !== undefined) params.since = q.since;
    if (q.until !== undefined) params.until = q.until;
    if (q.limit !== undefined) params.limit = parseInt(q.limit, 10);
    if (q.offset !== undefined) params.offset = parseInt(q.offset, 10);
    return service.list(params);
  });

  app.get<{ Params: { id: string } }>('/api/v1/audit-logs/:id', async (request) => {
    return service.getById(request.params.id);
  });

  app.post('/api/v1/audit-logs/purge', async (_request, reply) => {
    const deleted = await service.purgeExpired();
    reply.code(200);
    return { deleted };
  });
}
