import type { Request, Response, NextFunction } from 'express';
import * as exportService from '../services/export.service.js';

export async function exportCfdis(req: Request, res: Response, next: NextFunction) {
  try {
    const { tipo, estado, fechaInicio, fechaFin } = req.query;
    const buffer = await exportService.exportCfdisToExcel(req.tenantPool!, {
      tipo: tipo as string,
      estado: estado as string,
      fechaInicio: fechaInicio as string,
      fechaFin: fechaFin as string,
    });

    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=cfdis-${Date.now()}.xlsx`);
    res.send(buffer);
  } catch (error) {
    next(error);
  }
}

export async function exportReporte(req: Request, res: Response, next: NextFunction) {
  try {
    const { tipo, fechaInicio, fechaFin } = req.query;
    const now = new Date();
    const inicio = (fechaInicio as string) || `${now.getFullYear()}-01-01`;
    const fin = (fechaFin as string) || now.toISOString().split('T')[0];

    const buffer = await exportService.exportReporteToExcel(
      req.tenantPool!,
      tipo as 'estado-resultados' | 'flujo-efectivo',
      inicio,
      fin
    );

    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=${tipo}-${Date.now()}.xlsx`);
    res.send(buffer);
  } catch (error) {
    next(error);
  }
}
