import { Router, Request, Response } from 'express';
import { AuditAction } from '@prisma/client';
import { authenticate, requireRole } from '../../middleware/auth';
import * as auditService from './audit.service';

const router = Router();

router.use(authenticate);

router.get('/', requireRole('SUPER_ADMIN', 'OPERATOR'), async (req: Request, res: Response) => {
  const { action, instanceId, userId, from, to, page, limit } = req.query;

  const filters = {
    action: action && Object.values(AuditAction).includes(action as AuditAction)
      ? (action as AuditAction)
      : undefined,
    instanceId: instanceId as string | undefined,
    userId: userId as string | undefined,
    from: from as string | undefined,
    to: to as string | undefined,
  };

  const pageNum = Math.max(1, parseInt(page as string, 10) || 1);
  const limitNum = Math.min(100, Math.max(1, parseInt(limit as string, 10) || 50));

  const result = await auditService.listAuditLogs(filters, pageNum, limitNum);
  res.json(result);
});

export default router;
