import type { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import * as bancosService from '../services/bancos.service.js';
import { AppError } from '../middlewares/error.middleware.js';

const createSchema = z.object({
  banco: z.string().min(1, 'banco requerido').max(100),
  terminacionCuenta: z.string().min(1).max(4, 'terminacionCuenta max 4 digitos'),
});

const updateSchema = z.object({
  banco: z.string().min(1).max(100).optional(),
  terminacionCuenta: z.string().min(1).max(4).optional(),
});

export async function getBancos(req: Request, res: Response, next: NextFunction) {
  try {
    const contribuyenteId = (req.query.contribuyenteId as string) || null;
    const bancos = await bancosService.getBancos(req.tenantPool!, contribuyenteId);
    res.json(bancos);
  } catch (error) { next(error); }
}

export async function createBanco(req: Request, res: Response, next: NextFunction) {
  try {
    if (req.user!.role !== 'owner') return res.status(403).json({ message: 'No autorizado' });
    const data = createSchema.parse(req.body);
    const contribuyenteId = req.body.contribuyenteId as string | undefined;
    const result = await bancosService.createBanco(req.tenantPool!, { ...data, contribuyenteId });
    res.status(201).json(result);
  } catch (error) {
    if (error instanceof z.ZodError) return next(new AppError(400, error.errors[0].message));
    next(error);
  }
}

export async function updateBanco(req: Request, res: Response, next: NextFunction) {
  try {
    if (req.user!.role !== 'owner') return res.status(403).json({ message: 'No autorizado' });
    const id = parseInt(String(req.params.id));
    const data = updateSchema.parse(req.body);
    const result = await bancosService.updateBanco(req.tenantPool!, id, data);
    res.json(result);
  } catch (error) {
    if (error instanceof z.ZodError) return next(new AppError(400, error.errors[0].message));
    next(error);
  }
}

export async function deleteBanco(req: Request, res: Response, next: NextFunction) {
  try {
    if (req.user!.role !== 'owner') return res.status(403).json({ message: 'No autorizado' });
    const id = parseInt(String(req.params.id));
    await bancosService.deleteBanco(req.tenantPool!, id);
    res.json({ message: 'Banco eliminado' });
  } catch (error: any) {
    if (error.message?.includes('conciliaciones')) {
      return res.status(400).json({ message: error.message });
    }
    next(error);
  }
}
