import type { Request, Response, NextFunction } from 'express';
import { prisma } from '../config/database.js';
import { AppError } from '../middlewares/error.middleware.js';

export async function getDespachoAuditLog(req: Request, res: Response, next: NextFunction) {
  try {
    if (!req.user) return next(new AppError(401, 'No autenticado'));

    const tenantId = req.viewingTenantId || req.user.tenantId;

    // Only owner or cfo can see audit log of their despacho
    if (req.user.role !== 'owner' && req.user.role !== 'cfo') {
      return next(new AppError(403, 'Solo el dueño puede ver el registro de accesos'));
    }

    const from = req.query.from
      ? new Date(req.query.from as string)
      : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const to = req.query.to ? new Date(req.query.to as string) : new Date();
    const limit = Math.min(Number(req.query.limit) || 50, 200);

    const logs = await prisma.auditLog.findMany({
      where: {
        tenantId,
        action: { startsWith: 'admin.' },
        createdAt: { gte: from, lte: to },
      },
      orderBy: { createdAt: 'desc' },
      take: limit,
    });

    // Enrich with admin user info
    const userIds = [...new Set(logs.filter(l => l.userId).map(l => l.userId!))];
    const users =
      userIds.length > 0
        ? await prisma.user.findMany({
            where: { id: { in: userIds } },
            select: { id: true, nombre: true, email: true },
          })
        : [];
    const userMap = new Map(users.map(u => [u.id, u]));

    const enriched = logs.map(log => ({
      id: log.id,
      action: log.action,
      timestamp: log.createdAt.toISOString(),
      admin: log.userId
        ? {
            nombre: userMap.get(log.userId)?.nombre ?? 'Desconocido',
            email: userMap.get(log.userId)?.email ?? '',
          }
        : null,
      motivo: (log.metadata as any)?.motivo ?? null,
      ip: (log.metadata as any)?.ip ?? null,
      details: log.metadata,
    }));

    return res.json({
      data: enriched,
      total: enriched.length,
      from: from.toISOString(),
      to: to.toISOString(),
    });
  } catch (err) {
    return next(err);
  }
}
