import { Router } from 'express';
import { authenticate } from '../../middleware/auth';
import { requireRoles } from '../../middleware/rbac';
import { Role, ErrorCode } from '@saferoute/constants';
import { prisma } from '../../config/database';
import { sendSuccess, sendError, sendPaginated } from '../../utils/response';

export const auditLogRoutes = Router();

auditLogRoutes.get('/', authenticate, requireRoles(Role.OWNER, Role.CTO), async (req, res) => {
  try {
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 50;
    const skip = (page - 1) * limit;

    const where: any = {};
    if (req.query.entityType) where.entityType = req.query.entityType;
    if (req.query.action) where.action = { contains: req.query.action as string };
    if (req.query.actorId) where.actorId = req.query.actorId;

    const [logs, total] = await Promise.all([
      prisma.auditLog.findMany({
        where, skip, take: limit, orderBy: { createdAt: 'desc' },
        include: { actor: { select: { id: true, fullName: true, phone: true } } },
      }),
      prisma.auditLog.count({ where }),
    ]);

    sendPaginated(res, logs, total, page, limit);
  } catch (error) {
    sendError(res, ErrorCode.SERVER_ERROR, 'Failed to retrieve audit logs.');
  }
});
