import type { Request, Response, NextFunction } from 'express';
import { getMetricasMensuales } from '../services/metricas.service.js';
import { AppError } from '../middlewares/error.middleware.js';

export async function getMensuales(req: Request, res: Response, next: NextFunction) {
  try {
    const contribuyenteId = req.query.contribuyenteId as string;
    const anio = Number(req.query.anio);

    if (!contribuyenteId || !anio) {
      return next(new AppError(400, 'contribuyenteId y anio son requeridos'));
    }

    const regimenFiscal = req.query.regimen as string | undefined;
    const metricas = await getMetricasMensuales(req.tenantPool!, contribuyenteId, anio, regimenFiscal);

    const currentYear = new Date().getFullYear();
    return res.json({
      data: metricas,
      source: anio < currentYear ? 'cold' : 'hot',
      anio,
      contribuyenteId,
    });
  } catch (err) { return next(err); }
}
