import type { Request, Response, NextFunction } from 'express';
import * as dashService from '../services/admin-dashboard.service.js';
import { isPlatformStaff } from '../utils/platform-admin.js';
import { AppError } from '../middlewares/error.middleware.js';

async function requireStaff(req: Request) {
  if (!req.user?.userId) throw new AppError(401, 'No autenticado');
  const isStaff = await isPlatformStaff(req.user.userId);
  if (!isStaff) throw new AppError(403, 'Acceso restringido a staff de plataforma');
}

export async function getMetrics(req: Request, res: Response, next: NextFunction) {
  try {
    await requireStaff(req);
    const metrics = await dashService.getDashboardMetrics();
    return res.json(metrics);
  } catch (err) { return next(err); }
}

export async function listDespachos(req: Request, res: Response, next: NextFunction) {
  try {
    await requireStaff(req);
    const { vertical, status, search } = req.query as Record<string, string>;
    const despachos = await dashService.listAllDespachos({ vertical, status, search });
    return res.json({ data: despachos });
  } catch (err) { return next(err); }
}

export async function getActivity(req: Request, res: Response, next: NextFunction) {
  try {
    await requireStaff(req);
    const limit = Math.min(Number(req.query.limit) || 20, 100);
    const activity = await dashService.getRecentActivity(limit);
    return res.json({ data: activity });
  } catch (err) { return next(err); }
}
