import type { Request, Response, NextFunction } from 'express';
import * as conciliacionService from '../services/conciliacion.service.js';
import { prisma } from '../config/database.js';

export async function getCfdis(req: Request, res: Response, next: NextFunction) {
  try {
    const { tipo, fechaInicio, fechaFin, regimen, estado, contribuyenteId } = req.query;
    if (!tipo) return res.status(400).json({ message: 'tipo es requerido (EMITIDO|RECIBIDO)' });

    const data = await conciliacionService.getCfdisConConciliacion(req.tenantPool!, {
      tipo: tipo as string,
      fechaInicio: fechaInicio as string,
      fechaFin: fechaFin as string,
      regimen: regimen as string,
      estado: estado as string,
      contribuyenteId: contribuyenteId as string | undefined,
    });
    res.json(data);
  } catch (error) { next(error); }
}

export async function conciliar(req: Request, res: Response, next: NextFunction) {
  try {
    if (!['owner', 'cfo', 'contador', 'auxiliar', 'supervisor'].includes(req.user!.role)) {
      return res.status(403).json({ message: 'No autorizado' });
    }

    const { cfdiIds, fechaDePago, idBanco } = req.body;
    if (!cfdiIds?.length || !fechaDePago || !idBanco) {
      return res.status(400).json({ message: 'cfdiIds, fechaDePago e idBanco son requeridos' });
    }

    const tenant = await prisma.tenant.findUnique({
      where: { id: req.user!.tenantId },
      select: { createdAt: true },
    });
    const tenantCreatedYear = tenant ? tenant.createdAt.getFullYear() : new Date().getFullYear();

    const count = await conciliacionService.conciliar(req.tenantPool!, { cfdiIds, fechaDePago, idBanco }, tenantCreatedYear);
    res.json({ message: `${count} CFDIs conciliados`, count });
  } catch (error: any) {
    if (error.message && !error.message.includes('Internal')) {
      return res.status(400).json({ message: error.message });
    }
    next(error);
  }
}

export async function desconciliar(req: Request, res: Response, next: NextFunction) {
  try {
    if (!['owner', 'cfo', 'contador', 'auxiliar', 'supervisor'].includes(req.user!.role)) {
      return res.status(403).json({ message: 'No autorizado' });
    }
    const id = parseInt(String(req.params.id));
    await conciliacionService.desconciliar(req.tenantPool!, id);
    res.json({ message: 'CFDI desconciliado' });
  } catch (error) { next(error); }
}
