import { ForbiddenException } from '@nestjs/common';
import * as XLSX from 'xlsx';
import { submoduloHabilitado } from '../../auth/guards/submodulo.guard';
import { tieneAlgunPrivilegio } from '../../auth/guards/algun-privilegio.guard';
import { ymdInAsuncion } from '../../utils/utilidades';
import { TesChequeEstado } from '../dto/tes-cheque.dto';
import { errorDe } from './__helpers__/cheques-mock';
import { saldoMovidoPorOrigen } from './reglas-cheque';
import { TesMovimientosService } from './tes-movimientos.service';
import { TesReportesService } from './tes-reportes.service';

jest.mock('../../auth/guards/submodulo.guard', () => ({ ...jest.requireActual('../../auth/guards/submodulo.guard'), submoduloHabilitado: jest.fn() }));
jest.mock('../../auth/guards/algun-privilegio.guard', () => ({ ...jest.requireActual('../../auth/guards/algun-privilegio.guard'), tieneAlgunPrivilegio: jest.fn() }));
jest.mock('../../utils/utilidades', () => ({ ...jest.requireActual('../../utils/utilidades'), ymdInAsuncion: jest.fn() }));

const EMP = '0e000000-0000-4000-8000-000000000001';
const USER = 'u-1';
const CTA = 'c7a00000-0000-4000-8000-000000000001';
const FILTRO = { cuenta_id: CTA, fecha_desde: '2026-06-01', fecha_hasta: '2026-06-30' };

const fecha = (s: string) => new Date(`${s}T00:00:00.000Z`);

const mov = (id: string, dia: string, tipo: string, monto: number | string, origen_tipo: string | null = null, descripcion = id) => ({
  id,
  fecha: fecha(dia),
  tipo,
  origen_tipo,
  monto,
  descripcion,
  detalles: [],
});

const cuentaFila = (over = {}) => ({
  id: CTA,
  nombre: 'DOBA S.A. DOLARES',
  tipo: 'BANCO',
  moneda: 'USD',
  banco_id: 'b1',
  saldo_inicial: 0,
  saldo_actual: 7355.52,
  cuenta_contable_id: 'no-sale',
  mapeo_id: 'no-sale',
  ...over,
});

function armar(opts: { cuenta?: unknown; movs?: unknown[]; cheques?: unknown[]; config?: unknown; cuentas?: unknown[] } = {}) {
  const movs = (opts.movs ?? []) as Array<{ fecha: Date }>;
  const prisma = {
    tes_cuentas: { findFirst: jest.fn().mockResolvedValue('cuenta' in opts ? opts.cuenta : cuentaFila()), findMany: jest.fn().mockResolvedValue(opts.cuentas ?? []) },
    bancos: { findFirst: jest.fn().mockResolvedValue({ descripcion: 'Itaú' }) },
    tes_movimientos: {
      // Respeta el rango de fechas: el saldo anterior lee «antes de desde» y el período lee «desde».
      findMany: jest.fn(async ({ where }: { where: { fecha?: { lt?: Date; gte?: Date; lte?: Date } } }) => {
        const f = where.fecha ?? {};
        return movs.filter((m) => (!f.gte || m.fecha >= f.gte) && (!f.lt || m.fecha < f.lt) && (!f.lte || m.fecha <= f.lte));
      }),
    },
    tes_cheques: { findMany: jest.fn().mockResolvedValue(opts.cheques ?? []) },
  };
  const tesConfig = { get: jest.fn().mockResolvedValue(opts.config ?? null) };
  return { prisma, tesConfig, service: new TesReportesService(prisma as never, tesConfig as never) };
}

const hoy = ymdInAsuncion as jest.Mock;
const submodulo = submoduloHabilitado as jest.Mock;
const privilegio = tieneAlgunPrivilegio as jest.Mock;

beforeEach(() => {
  hoy.mockReturnValue('2026-11-04');
  submodulo.mockResolvedValue({ habilitado: true, fechaFinPrueba: null });
  privilegio.mockResolvedValue(true);
});

describe('extractoCuenta', () => {
  it('TRANSFERENCIA_DESTINO de 18.500 → INGRESO, suma; TRANSFERENCIA_ORIGEN resta y va en egreso', async () => {
    const { service } = armar({
      movs: [mov('a', '2026-06-01', 'TRANSFERENCIA', 18500, 'TRANSFERENCIA_DESTINO'), mov('b', '2026-06-02', 'TRANSFERENCIA', 500, 'TRANSFERENCIA_ORIGEN')],
    });
    const r = await service.extractoCuenta(EMP, FILTRO);
    expect(r.lineas[0]).toMatchObject({ id: 'a', tipo: 'TRANSFERENCIA', sentido: 'INGRESO', ingreso: 18500, egreso: 0, saldo: 18500 });
    expect(r.lineas[1]).toMatchObject({ id: 'b', tipo: 'TRANSFERENCIA', sentido: 'EGRESO', ingreso: 0, egreso: 500, saldo: 18000 });
    expect(r.saldoFinal).toBe(18000);
  });

  it('DOBA S.A. DOLARES: entradas por transferencia dan el saldo real, no el negativo de hoy', async () => {
    // La fórmula vieja restaba las transferencias de entrada: −1.000 − 500 + 8.855,52 no da 7.355,52; con sentido, sí.
    const { service } = armar({
      movs: [
        mov('a', '2026-07-01', 'TRANSFERENCIA', '8855.52', 'TRANSFERENCIA_DESTINO'),
        mov('b', '2026-07-02', 'EGRESO', '1000.00'),
        mov('c', '2026-07-03', 'TRANSFERENCIA', '500.00', 'TRANSFERENCIA_ORIGEN'),
      ],
    });
    const r = await service.extractoCuenta(EMP, { ...FILTRO, fecha_desde: '2026-07-01', fecha_hasta: '2026-07-31' });
    expect(r.saldoFinal).toBe(7355.52);
    expect(r.saldoFinal).toBe(r.cuenta.saldo_actual);
  });

  it('saldoAnterior suma la TRANSFERENCIA_DESTINO previa', async () => {
    const { service } = armar({
      cuenta: cuentaFila({ saldo_inicial: 100 }),
      movs: [mov('p', '2026-05-01', 'TRANSFERENCIA', 50, 'TRANSFERENCIA_DESTINO'), mov('q', '2026-05-02', 'EGRESO', 20)],
    });
    expect((await service.extractoCuenta(EMP, FILTRO)).saldoAnterior).toBe(130);
  });

  it('el mismo fixture da los mismos saldos que TesMovimientosService.getExtracto', async () => {
    const { service, prisma } = armar({
      cuenta: cuentaFila({ saldo_inicial: '1000.10' }),
      movs: [
        mov('p', '2026-05-01', 'TRANSFERENCIA', '0.20', 'TRANSFERENCIA_DESTINO'),
        mov('a', '2026-06-01', 'INGRESO', '0.10'),
        mov('b', '2026-06-01', 'TRANSFERENCIA', '18500.33', 'TRANSFERENCIA_ORIGEN'),
        mov('c', '2026-06-15', 'TRANSFERENCIA', '20000.01', 'TRANSFERENCIA_DESTINO'),
        mov('d', '2026-06-30', 'EGRESO', '0.07'),
      ],
    });
    const otro = new TesMovimientosService(prisma as never, {} as never, {} as never, {} as never);
    const r = await service.extractoCuenta(EMP, FILTRO);
    const s2 = await otro.getExtracto(EMP, CTA, FILTRO.fecha_desde, FILTRO.fecha_hasta);
    expect(r.saldoAnterior).toBe(s2.saldo_apertura);
    expect(r.saldoFinal).toBe(s2.saldo_cierre);
    expect(r.lineas.map((l) => [l.id, l.saldo, l.sentido])).toEqual(s2.movimientos.map((m) => [m.id, m.saldo_acumulado, m.sentido]));
  });

  it('findMany ordena por fecha, confirmado_en, created_at, id: el orden de getExtracto', async () => {
    const { service, prisma } = armar();
    await service.extractoCuenta(EMP, FILTRO);
    const periodo = prisma.tes_movimientos.findMany.mock.calls.map((c) => c[0] as never as { where: { fecha: { gte?: Date } }; orderBy?: unknown }).find((a) => a.where.fecha.gte);
    expect(periodo?.orderBy).toEqual([{ fecha: 'asc' }, { confirmado_en: 'asc' }, { created_at: 'asc' }, { id: 'asc' }]);
  });

  it('216722652.56000006 sale 216722652.56', async () => {
    const { service } = armar({ cuenta: cuentaFila({ saldo_inicial: '216722652.56000006' }), movs: [mov('a', '2026-06-01', 'INGRESO', 0)] });
    const r = await service.extractoCuenta(EMP, FILTRO);
    expect(r.saldoAnterior).toBe(216722652.56);
    expect(r.saldoFinal).toBe(216722652.56);
    expect(r.lineas[0].saldo).toBe(216722652.56);
  });

  it('cuenta ajena → 400 CUENTA_INVALIDA, sin leer movimientos', async () => {
    const { service, prisma } = armar({ cuenta: null });
    expect(await errorDe(service.extractoCuenta(EMP, FILTRO))).toMatchObject({ status: 400, codigo: 'CUENTA_INVALIDA', campo: 'cuenta_id' });
    expect(prisma.tes_movimientos.findMany).not.toHaveBeenCalled();
  });

  it('fecha_desde > fecha_hasta → 400 PERIODO_INVALIDO', async () => {
    const { service } = armar();
    expect(await errorDe(service.extractoCuenta(EMP, { ...FILTRO, fecha_desde: '2026-07-01' }))).toMatchObject({ status: 400, codigo: 'PERIODO_INVALIDO', campo: 'fecha_desde' });
  });

  it('cuenta trae saldo_actual, banco y moneda; nada contable', async () => {
    const { service } = armar();
    const { cuenta } = await service.extractoCuenta(EMP, FILTRO);
    expect(cuenta).toEqual({ id: CTA, nombre: 'DOBA S.A. DOLARES', tipo: 'BANCO', moneda: 'USD', banco: 'Itaú', saldo_actual: 7355.52 });
  });

  it('totalIngresos y totalEgresos por sentido', async () => {
    const { service } = armar({
      movs: [
        mov('a', '2026-06-01', 'TRANSFERENCIA', '100.10', 'TRANSFERENCIA_DESTINO'),
        mov('b', '2026-06-02', 'INGRESO', '0.20'),
        mov('c', '2026-06-03', 'EGRESO', 30),
        mov('d', '2026-06-04', 'TRANSFERENCIA', 20, 'TRANSFERENCIA_ORIGEN'),
      ],
    });
    const r = await service.extractoCuenta(EMP, FILTRO);
    expect(r.totalIngresos).toBe(100.3);
    expect(r.totalEgresos).toBe(50);
  });
});

const cheque = (over = {}) => ({
  id: 'ch',
  numero_cheque: '0001',
  tipo: 'RECIBIDO',
  banco_emisor: 'Itaú',
  titular: 'Juan',
  monto: 1000,
  moneda: 'PYG',
  fecha_emision: fecha('2026-05-01'),
  fecha_vencimiento: fecha('2026-12-31'),
  created_at: new Date('2026-05-01T12:00:00Z'),
  estado: 'EN_CARTERA',
  origen_tipo: null,
  movimiento_id: null,
  cuenta: { nombre: 'Cuenta Uno' },
  ...over,
});

describe('carteraCheques', () => {
  it('2 PYG + 1 USD en cartera → porMoneda, recibidos y emitidos por separado', async () => {
    const { service } = armar({ cheques: [cheque({ monto: 1000 }), cheque({ monto: 2000, tipo: 'EMITIDO' }), cheque({ monto: '1250.50', moneda: 'USD' })] });
    const { resumen } = await service.carteraCheques(EMP, {});
    expect(resumen.porMoneda).toEqual([
      { moneda: 'PYG', cantidad: 2, total: 3000, recibidos: 1000, emitidos: 2000 },
      { moneda: 'USD', cantidad: 1, total: 1250.5, recibidos: 1250.5, emitidos: 0 },
    ]);
    expect(resumen.enCartera).toBe(3);
  });

  it('DIFERIDO no entra a porMoneda y cuenta en diferidos', async () => {
    const { service } = armar({ cheques: [cheque({ estado: 'DIFERIDO' })] });
    const { resumen } = await service.carteraCheques(EMP, {});
    expect(resumen.porMoneda).toEqual([]);
    expect(resumen.diferidos).toBe(1);
    expect(resumen.enCartera).toBe(0);
  });

  it('DEBITADO en debitados, DEPOSITADO en depositados', async () => {
    const { service } = armar({ cheques: [cheque({ estado: 'DEBITADO' }), cheque({ estado: 'DEPOSITADO' }), cheque({ estado: 'DEPOSITADO' })] });
    const { resumen } = await service.carteraCheques(EMP, {});
    expect(resumen).toMatchObject({ debitados: 1, depositados: 2 });
  });

  it('resumen no trae totalCartera ni vencenEn7Dias (sumaban monedas y la ventana era fija)', async () => {
    const { service } = armar({ cheques: [cheque({ monto: 1000 })] });
    const { resumen } = await service.carteraCheques(EMP, {});
    expect(resumen).not.toHaveProperty('totalCartera');
    expect(resumen).not.toHaveProperty('vencenEn7Dias');
  });

  it('tes_config con 21 días: a 20 cuenta, a 22 no', async () => {
    const { service } = armar({
      config: { dias_alerta_cheques: 21 },
      cheques: [cheque({ fecha_vencimiento: fecha('2026-11-24') }), cheque({ fecha_vencimiento: fecha('2026-11-26') })],
    });
    const { resumen } = await service.carteraCheques(EMP, {});
    expect(resumen.vencenPronto).toBe(1);
    expect(resumen.diasAlerta).toBe(21);
  });

  it('el borde: justo a N días cuenta', async () => {
    const { service } = armar({ cheques: [cheque({ fecha_vencimiento: fecha('2026-11-11') }), cheque({ fecha_vencimiento: fecha('2026-11-12') })] });
    expect((await service.carteraCheques(EMP, {})).resumen.vencenPronto).toBe(1);
  });

  it('sin tes_config: 7 días', async () => {
    const { service } = armar();
    expect((await service.carteraCheques(EMP, {})).resumen.diasAlerta).toBe(7);
  });

  it('vence hoy (ymdInAsuncion a las 23:30) cuenta; venció ayer, no', async () => {
    hoy.mockReturnValue('2026-11-04');
    const { service } = armar({ cheques: [cheque({ fecha_vencimiento: fecha('2026-11-04') }), cheque({ fecha_vencimiento: fecha('2026-11-03') })] });
    expect((await service.carteraCheques(EMP, {})).resumen.vencenPronto).toBe(1);
  });

  it('DIFERIDO a 3 días no cuenta en vencenPronto', async () => {
    const { service } = armar({ cheques: [cheque({ estado: 'DIFERIDO', fecha_vencimiento: fecha('2026-11-07') })] });
    expect((await service.carteraCheques(EMP, {})).resumen.vencenPronto).toBe(0);
  });

  it('un EN_CARTERA con saldo_movido_por_origen que vence en 3 días cuenta (F21: no es avisosVencimiento)', async () => {
    const c = cheque({ fecha_vencimiento: fecha('2026-11-07'), origen_tipo: 'RENDICION_ADELANTO' });
    // El mismo cheque, para `TesChequeService`, es el que el listado marca con `saldo_movido_por_origen`.
    expect(saldoMovidoPorOrigen(c.estado, c.origen_tipo, undefined)).toBe(true);
    const { service } = armar({ cheques: [c] });
    expect((await service.carteraCheques(EMP, {})).resumen.vencenPronto).toBe(1);
  });

  it('sin vencimiento no cuenta y no lanza', async () => {
    const { service } = armar({ cheques: [cheque({ fecha_vencimiento: null })] });
    const r = await service.carteraCheques(EMP, {});
    expect(r.resumen.vencenPronto).toBe(0);
    expect(r.cheques[0].vencimiento).toBeNull();
  });

  it('el where lleva el estado DIFERIDO y los demás filtros', async () => {
    const { service, prisma } = armar();
    await service.carteraCheques(EMP, { estado: TesChequeEstado.DIFERIDO, tipo_cheque: 'EMITIDO', cuenta_id: CTA, fecha_desde: '2026-01-01', fecha_hasta: '2026-02-01' });
    expect(prisma.tes_cheques.findMany.mock.calls[0][0].where).toEqual({
      empresa_id: EMP,
      estado: 'DIFERIDO',
      tipo: 'EMITIDO',
      cuenta_id: CTA,
      fecha_vencimiento: { gte: fecha('2026-01-01'), lte: fecha('2026-02-01') },
    });
  });

  it('fecha_desde > fecha_hasta → 400 PERIODO_INVALIDO', async () => {
    const { service } = armar();
    expect(await errorDe(service.carteraCheques(EMP, { fecha_desde: '2026-03-01', fecha_hasta: '2026-02-01' }))).toMatchObject({
      status: 400,
      codigo: 'PERIODO_INVALIDO',
      campo: 'fecha_desde',
    });
  });

  it('TES_CHEQUES no habilitado → 403, sin leer cheques', async () => {
    submodulo.mockResolvedValue({ habilitado: false, causa: 'excluido', mensaje: 'no' });
    const { service, prisma } = armar();
    await expect(service.carteraCheques(EMP, {})).rejects.toBeInstanceOf(ForbiddenException);
    expect(submodulo).toHaveBeenCalledWith(prisma, EMP, 'TES_CHEQUES');
    expect(prisma.tes_cheques.findMany).not.toHaveBeenCalled();
  });

  it('umbral de aprobación y moneda_base_reportes no cambian nada', async () => {
    const { service } = armar({ config: { dias_alerta_cheques: 7, monto_umbral_aprobacion: 1, moneda_base_reportes: 'USD' }, cheques: [cheque({ monto: 1000 })] });
    const { resumen } = await service.carteraCheques(EMP, {});
    expect(resumen.porMoneda).toEqual([{ moneda: 'PYG', cantidad: 1, total: 1000, recibidos: 1000, emitidos: 0 }]);
    expect(resumen.diasAlerta).toBe(7);
  });

  it('F6: un cheque sin cuenta sale con cuenta: null (la clave está)', async () => {
    const { service } = armar({ cheques: [cheque({ cuenta: null })] });
    const [c] = (await service.carteraCheques(EMP, {})).cheques;
    expect(c).toHaveProperty('cuenta', null);
  });

  it('cada fila trae todos los campos del contrato', async () => {
    const { service } = armar({ cheques: [cheque()] });
    const [c] = (await service.carteraCheques(EMP, {})).cheques;
    expect(Object.keys(c).sort()).toEqual(['banco', 'cuenta', 'emision', 'estado', 'id', 'moneda', 'monto', 'numero', 'recepcion', 'tipo', 'titular', 'vencimiento']);
  });
});

describe('opciones', () => {
  it('sin saldo_*, cuenta_contable_id ni mapeo_id', async () => {
    const { service, prisma } = armar({
      cuentas: [{ id: 'a', nombre: 'A', moneda: 'PYG', tipo: 'BANCO', activo: true, saldo_actual: 1, saldo_inicial: 2, cuenta_contable_id: 'x', mapeo_id: 'y' }],
    });
    const r = await service.opciones(EMP);
    expect(r.cuentas).toEqual([{ id: 'a', nombre: 'A', moneda: 'PYG', tipo: 'BANCO', activo: true }]);
    expect(prisma.tes_cuentas.findMany.mock.calls[0][0].select).toEqual({ id: true, nombre: true, moneda: true, tipo: true, activo: true });
  });

  it('activas primero, por nombre; de la empresa', async () => {
    const { service, prisma } = armar();
    await service.opciones(EMP);
    expect(prisma.tes_cuentas.findMany.mock.calls[0][0]).toMatchObject({ where: { empresa_id: EMP }, orderBy: [{ activo: 'desc' }, { nombre: 'asc' }] });
  });

  it('sin tes_config: 7 días; con ella, los suyos', async () => {
    expect((await armar().service.opciones(EMP)).dias_alerta_cheques).toBe(7);
    expect((await armar({ config: { dias_alerta_cheques: 21 } }).service.opciones(EMP)).dias_alerta_cheques).toBe(21);
  });
});

describe('Excel', () => {
  const hojaDe = (buf: Buffer, nombre: string) => XLSX.utils.sheet_to_json<(string | number)[]>(XLSX.read(buf, { type: 'buffer' }).Sheets[nombre], { header: 1 });

  it('extractoCuentaExcel con EXPORTAR y sin LIBRO_BANCO_VER → 403 SIN_PERMISO_VER_REPORTE', async () => {
    privilegio.mockResolvedValue(false);
    const { service, prisma } = armar();
    expect(await errorDe(service.extractoCuentaExcel(EMP, USER, FILTRO))).toMatchObject({ status: 403, codigo: 'SIN_PERMISO_VER_REPORTE' });
    expect(privilegio).toHaveBeenCalledWith(prisma, USER, ['TES_REP_LIBRO_BANCO_VER']);
    expect(prisma.tes_movimientos.findMany).not.toHaveBeenCalled();
  });

  it('carteraChequesExcel sin CHQ_CHEQUE_VER → 403 SIN_PERMISO_VER_REPORTE', async () => {
    privilegio.mockResolvedValue(false);
    const { service, prisma } = armar();
    expect(await errorDe(service.carteraChequesExcel(EMP, USER, {}))).toMatchObject({ status: 403, codigo: 'SIN_PERMISO_VER_REPORTE' });
    expect(privilegio).toHaveBeenCalledWith(prisma, USER, ['TES_CHQ_CHEQUE_VER']);
    expect(prisma.tes_cheques.findMany).not.toHaveBeenCalled();
  });

  it('carteraChequesExcel sin el submódulo TES_CHEQUES → 403', async () => {
    submodulo.mockResolvedValue({ habilitado: false, causa: 'excluido', mensaje: 'no' });
    await expect(armar().service.carteraChequesExcel(EMP, USER, {})).rejects.toBeInstanceOf(ForbiddenException);
  });

  it('extracto con q: el archivo trae esas filas, con el saldo de pantalla', async () => {
    const { service } = armar({
      movs: [
        mov('a', '2026-06-01', 'TRANSFERENCIA', 100, 'TRANSFERENCIA_DESTINO', 'COMPRA DOLARES'),
        mov('b', '2026-06-02', 'EGRESO', 30, null, 'otra'),
        mov('c', '2026-06-03', 'EGRESO', 20, null, 'Compra útiles'),
      ],
    });
    const filas = hojaDe(await service.extractoCuentaExcel(EMP, USER, { ...FILTRO, q: 'compra' }), 'Extracto');
    expect(filas).toHaveLength(3);
    expect(filas.slice(1).map((f) => f[7])).toEqual([100, 50]);
  });

  it('cartera con q y un cheque sin vencimiento: no da 500 y trae esa fila', async () => {
    const { service } = armar({ cheques: [cheque({ fecha_vencimiento: null, numero_cheque: '7777' }), cheque({ numero_cheque: '8888' })] });
    const filas = hojaDe(await service.carteraChequesExcel(EMP, USER, { q: '7777' }), 'Cheques');
    expect(filas).toHaveLength(2);
    expect(filas[1][0]).toBe('7777');
    expect(filas[1][6]).toBe('—');
  });
});
