/**
 * Document Audit Routes
 * Audit logs and compliance reporting
 */

import { FastifyInstance } from 'fastify';
import {
  getDocumentAuditLogs,
  searchDocumentAuditLogs,
  getAuditStatistics,
} from '@the-order/database';
import { authenticateJWT, requireRole } from '@the-order/shared';

export async function registerAuditRoutes(server: FastifyInstance): Promise<void> {
  server.get('/documents/:id/audit', {
    preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
    schema: {
      params: { type: 'object', properties: { id: { type: 'string' } } },
      querystring: {
        type: 'object',
        properties: { action: { type: 'string' }, start_date: { type: 'string' }, end_date: { type: 'string' } },
      },
      tags: ['audit'],
    },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const query = request.query as any;
    const logs = await getDocumentAuditLogs(id, query);
    return reply.send({ logs });
  });

  server.get('/audit/search', {
    preHandler: [authenticateJWT, requireRole('admin')],
    schema: {
      querystring: {
        type: 'object',
        properties: {
          document_id: { type: 'string' },
          action: { type: 'string' },
          performed_by: { type: 'string' },
          start_date: { type: 'string' },
          end_date: { type: 'string' },
        },
      },
      tags: ['audit'],
    },
  }, async (request, reply) => {
    const query = request.query as any;
    const result = await searchDocumentAuditLogs(query);
    return reply.send(result);
  });

  server.get('/audit/statistics', {
    preHandler: [authenticateJWT, requireRole('admin')],
    schema: { tags: ['audit'] },
  }, async (request, reply) => {
    const stats = await getAuditStatistics();
    return reply.send(stats);
  });
}

