import type { FastifyInstance } from 'fastify';
import { getAuditLogs, getAuditLogsByEntity, getAuditLogsByUser } from './repository.js';
import { QueryParamsSchema } from './types.js';
import { requireAdmin } from '../../lib/auth.js';

export async function auditRoutes(fastify: FastifyInstance) {
  // Get all audit logs (admin only)
  fastify.get('/audit-logs', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    const params = QueryParamsSchema.parse(req.query);
    const logs = await getAuditLogs(params.limit);
    return reply.send(logs);
  });

  // Get audit logs by entity (admin only)
  fastify.get('/audit-logs/entity/:entityType/:entityId', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    const { entityType, entityId } = req.params as { entityType: string; entityId: string };
    const params = QueryParamsSchema.parse(req.query);
    const logs = await getAuditLogsByEntity(entityType, entityId, params.limit);
    return reply.send(logs);
  });

  // Get audit logs by user (admin only)
  fastify.get('/audit-logs/user/:userId', {
    preHandler: async (req) => requireAdmin(req),
  }, async (req, reply) => {
    const { userId } = req.params as { userId: string };
    const params = QueryParamsSchema.parse(req.query);
    const logs = await getAuditLogsByUser(userId, params.limit);
    return reply.send(logs);
  });
}
