import { BadRequestException } from '@nestjs/common';
import { submoduloHabilitado } from '../../auth/guards/submodulo.guard';
import { TesReglasService } from './tes-reglas.service';

// Habilitado por defecto (F19): cada caso de «Condición» lo pisa.
jest.mock('../../auth/guards/submodulo.guard', () => ({ submoduloHabilitado: jest.fn() }));
const habilitado = submoduloHabilitado as jest.Mock;
beforeEach(() => {
  habilitado.mockReset();
  habilitado.mockResolvedValue({ habilitado: true, fechaFinPrueba: null });
});

/** Reglas "Pago de gasto" por moneda (Task 8): una por (empresa, tipo, medio, moneda). */
const MON_PYG = '11111111-1111-4111-8111-111111111111';
const MON_USD = '22222222-2222-4222-8222-222222222222';
const MONEDAS = [MON_PYG, MON_USD];

function armar() {
  const filas: any[] = [];
  const coincide = (r: any, where: any) => Object.entries(where).every(([k, v]) => (r[k] ?? null) === v);
  const prisma: any = {
    tes_reglas: {
      findFirst: jest.fn().mockImplementation(({ where }) => filas.find((r) => coincide(r, where)) ?? null),
      create: jest.fn().mockImplementation(({ data }) => {
        const fila = { id: `r${filas.length + 1}`, ...data };
        filas.push(fila);
        return fila;
      }),
      update: jest.fn().mockImplementation(({ where, data }) =>
        Object.assign(
          filas.find((r) => r.id === where.id),
          data,
        ),
      ),
      findMany: jest.fn().mockImplementation(() => filas),
    },
    moneda: {
      findUnique: jest.fn().mockImplementation(({ where }) => (MONEDAS.includes(where.id) ? { id: where.id } : null)),
    },
    // Las cuentas de la empresa 'emp' (activas); 'ajena' es de otra empresa.
    tes_cuentas: {
      findFirst: jest
        .fn()
        .mockImplementation(({ where }) => (where.empresa_id === 'emp' && where.id !== 'ajena' && where.activo ? { id: where.id } : null)),
    },
    medio_pago: { findUnique: jest.fn().mockImplementation(({ where }) => (where.id === 'mp-inexistente' ? null : { id: where.id })) },
  };
  return { service: new TesReglasService(prisma), filas, prisma };
}

describe('TesReglasService — moneda en "Pago de gasto"', () => {
  it('upsert con moneda en PAGO_PROVEEDOR → 400', async () => {
    const { service, prisma } = armar();
    const intento = service.upsert('emp', { tipo_operacion: 'PAGO_PROVEEDOR', moneda_id: MON_USD, cuenta_id: 'c1' });
    await expect(intento).rejects.toThrow(BadRequestException);
    await expect(intento).rejects.toThrow('La moneda solo aplica a la regla "Pago de gasto".');
    expect(prisma.tes_reglas.create).not.toHaveBeenCalled();
  });

  it('dos reglas PAGO_GASTO del mismo medio en PYG y USD conviven', async () => {
    const { service, filas, prisma } = armar();
    await service.upsert('emp', {
      tipo_operacion: 'PAGO_GASTO',
      medio_pago_id: 'mp',
      moneda_id: MON_PYG,
      cuenta_id: 'c-pyg',
    });
    await service.upsert('emp', {
      tipo_operacion: 'PAGO_GASTO',
      medio_pago_id: 'mp',
      moneda_id: MON_USD,
      cuenta_id: 'c-usd',
    });
    expect(filas).toHaveLength(2);
    expect(filas.map((r) => [r.moneda_id, r.cuenta_id])).toEqual([
      [MON_PYG, 'c-pyg'],
      [MON_USD, 'c-usd'],
    ]);
    // Volver a guardar la de USD la actualiza, no crea otra.
    await service.upsert('emp', {
      tipo_operacion: 'PAGO_GASTO',
      medio_pago_id: 'mp',
      moneda_id: MON_USD,
      cuenta_id: 'c-usd-2',
    });
    expect(filas).toHaveLength(2);
    expect(filas[1].cuenta_id).toBe('c-usd-2');
    expect(prisma.tes_reglas.findFirst).toHaveBeenLastCalledWith(
      expect.objectContaining({
        where: { empresa_id: 'emp', tipo_operacion: 'PAGO_GASTO', medio_pago_id: 'mp', moneda_id: MON_USD },
      }),
    );
  });

  it('sin moneda la regla vale para cualquiera y es distinta de la de USD', async () => {
    const { service, filas } = armar();
    await service.upsert('emp', { tipo_operacion: 'PAGO_GASTO', moneda_id: MON_USD, cuenta_id: 'c-usd' });
    await service.upsert('emp', { tipo_operacion: 'PAGO_GASTO', cuenta_id: 'c-gral' });
    expect(filas.map((r) => r.moneda_id)).toEqual([MON_USD, null]);
  });

  it('getRegla y getCuentaSugerida solo miran la regla sin moneda; findAll incluye la moneda', async () => {
    const { service, prisma } = armar();
    await service.getRegla('emp', 'PAGO_GASTO');
    expect(prisma.tes_reglas.findFirst).toHaveBeenLastCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ medio_pago_id: null, moneda_id: null }) }),
    );
    await service.getCuentaSugerida('emp', 'PAGO_GASTO');
    expect(prisma.tes_reglas.findFirst).toHaveBeenLastCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ medio_pago_id: null, moneda_id: null }) }),
    );
    await service.findAll('emp');
    expect(prisma.tes_reglas.findMany.mock.calls[0][0].include.moneda).toEqual({ select: { id: true, codigo: true } });
  });

  it('findAll trae si la cuenta de cada regla está activa: el listado no necesita leer /tes/cuentas', async () => {
    const { service, prisma } = armar();
    await service.findAll('emp');
    expect(prisma.tes_reglas.findMany.mock.calls[0][0].include.cuenta).toEqual({ select: { id: true, nombre: true, moneda: true, tipo: true, activo: true } });
  });

  it('moneda_id que no es uuid o no existe → 400 (no 500)', async () => {
    const { service, prisma } = armar();
    for (const moneda_id of ['usd', '33333333-3333-4333-8333-333333333333']) {
      await expect(service.upsert('emp', { tipo_operacion: 'PAGO_GASTO', moneda_id, cuenta_id: 'c1' })).rejects.toThrow(
        'La moneda elegida no existe.',
      );
    }
    expect(prisma.tes_reglas.create).not.toHaveBeenCalled();
  });
});

describe('TesReglasService — referencias de la regla (I10)', () => {
  it('cuenta de otra empresa → 400 y no graba', async () => {
    const { service, filas } = armar();
    await expect(service.upsert('emp', { tipo_operacion: 'PAGO_PROVEEDOR', cuenta_id: 'ajena' })).rejects.toThrow(
      'La cuenta elegida no existe, está inactiva o no es de la empresa.',
    );
    expect(filas).toHaveLength(0);
  });

  it('medio de pago inexistente → 400', async () => {
    const { service } = armar();
    await expect(
      service.upsert('emp', { tipo_operacion: 'PAGO_GASTO', medio_pago_id: 'mp-inexistente', cuenta_id: 'c1' }),
    ).rejects.toThrow('El medio de pago elegido no existe.');
  });

  it('getCuentaSugerida no devuelve una cuenta de otra empresa grabada antes de esta validación', async () => {
    const { service, prisma } = armar();
    prisma.tes_reglas.findFirst.mockResolvedValue({ cuenta_id: 'ajena', activo: true, cuenta: { empresa_id: 'otra', activo: true } });
    await expect(service.getCuentaSugerida('emp', 'PAGO_PROVEEDOR')).resolves.toBeNull();
  });
});

describe('UpsertTesReglaDto (I10)', () => {
  const { plainToInstance } = require('class-transformer');
  const { validateSync } = require('class-validator');
  const { UpsertTesReglaDto } = require('../dto/upsert-tes-regla.dto');
  const errores = (v: object) => validateSync(plainToInstance(UpsertTesReglaDto, v)).map((e: any) => e.property);

  it('valida tipo, uuids y activo', () => {
    expect(errores({ tipo_operacion: 'COBRO_EFECTIVO' })).toEqual(['tipo_operacion']);
    expect(errores({ tipo_operacion: 'PAGO_GASTO', cuenta_id: 'x', medio_pago_id: 'y', moneda_id: 'z', activo: 'si' })).toEqual([
      'medio_pago_id',
      'moneda_id',
      'cuenta_id',
      'activo',
    ]);
    expect(errores({ tipo_operacion: 'PAGO_GASTO', cuenta_id: null, medio_pago_id: null, activo: false })).toEqual([]);
  });
});


describe('TesReglasService — submódulo del tipo (Condición)', () => {
  it('PAGO_PROVEEDOR con COMP_ORDEN_PAGO deshabilitado → REGLA_SIN_MODULO con campo tipo_operacion, sin escribir', async () => {
    const { service, prisma } = armar();
    habilitado.mockResolvedValue({ habilitado: false, causa: 'excluido', mensaje: 'Órdenes de pago no está en el plan' });
    await expect(service.upsert('emp', { tipo_operacion: 'PAGO_PROVEEDOR', cuenta_id: 'c1' })).rejects.toMatchObject({
      response: { codigo: 'REGLA_SIN_MODULO', campo: 'tipo_operacion', submodulo: 'COMP_ORDEN_PAGO' },
    });
    expect(habilitado).toHaveBeenCalledWith(prisma, 'emp', 'COMP_ORDEN_PAGO');
    expect(prisma.tes_reglas.create).not.toHaveBeenCalled();
    expect(prisma.tes_reglas.update).not.toHaveBeenCalled();
  });

  it.each([
    ['COBRO_CLIENTE', 'COB_RECIBOS'],
    ['PAGO_PROVEEDOR', 'COMP_ORDEN_PAGO'],
    ['PAGO_GASTO', 'TES_GASTOS'],
  ])('%s con %s habilitado → guarda', async (tipo, submodulo) => {
    const { service, filas } = armar();
    await service.upsert('emp', { tipo_operacion: tipo, cuenta_id: 'c1' });
    expect(habilitado).toHaveBeenCalledWith(expect.anything(), 'emp', submodulo);
    expect(filas).toHaveLength(1);
  });

  it('la eliminación no mira el submódulo', async () => {
    const { service, prisma } = armar();
    prisma.tes_reglas.findFirst.mockResolvedValue({ id: 'r1' });
    prisma.tes_reglas.delete = jest.fn().mockResolvedValue({});
    habilitado.mockResolvedValue({ habilitado: false, causa: 'excluido', mensaje: 'x' });
    await expect(service.remove('emp', 'r1')).resolves.toEqual({ ok: true });
    expect(habilitado).not.toHaveBeenCalled();
  });
});

describe('TesReglasService — errores con código', () => {
  const cuerpo = async (promesa: Promise<unknown>) => {
    try {
      await promesa;
    } catch (e: any) {
      expect(e).toBeInstanceOf(BadRequestException);
      return e.getResponse();
    }
    throw new Error('no lanzó');
  };

  it('tipo sin efecto → REGLA_TIPO_INVALIDO con campo tipo_operacion', async () => {
    const { service } = armar();
    const r = await cuerpo(service.upsert('emp', { tipo_operacion: 'COBRO_EFECTIVO', cuenta_id: 'c1' }));
    expect(r).toMatchObject({ codigo: 'REGLA_TIPO_INVALIDO', campo: 'tipo_operacion' });
    expect(habilitado).not.toHaveBeenCalled();
  });

  it('moneda fuera de PAGO_GASTO → REGLA_MONEDA_NO_APLICA con el mismo mensaje', async () => {
    const { service } = armar();
    const r = await cuerpo(service.upsert('emp', { tipo_operacion: 'COBRO_CLIENTE', moneda_id: MON_USD }));
    expect(r).toMatchObject({ codigo: 'REGLA_MONEDA_NO_APLICA', campo: 'moneda_id', message: 'La moneda solo aplica a la regla "Pago de gasto".' });
  });

  it('moneda inexistente → MONEDA_NO_ENCONTRADA', async () => {
    const { service } = armar();
    const r = await cuerpo(service.upsert('emp', { tipo_operacion: 'PAGO_GASTO', moneda_id: 'usd' }));
    expect(r).toMatchObject({ codigo: 'MONEDA_NO_ENCONTRADA', campo: 'moneda_id', message: 'La moneda elegida no existe.' });
  });

  it('cuenta ajena → CUENTA_INVALIDA con el mismo mensaje', async () => {
    const { service } = armar();
    const r = await cuerpo(service.upsert('emp', { tipo_operacion: 'PAGO_PROVEEDOR', cuenta_id: 'ajena' }));
    expect(r).toMatchObject({
      codigo: 'CUENTA_INVALIDA',
      campo: 'cuenta_id',
      message: 'La cuenta elegida no existe, está inactiva o no es de la empresa.',
    });
  });

  it('medio inexistente → MEDIO_PAGO_INVALIDO', async () => {
    const { service } = armar();
    const r = await cuerpo(service.upsert('emp', { tipo_operacion: 'PAGO_GASTO', medio_pago_id: 'mp-inexistente', cuenta_id: 'c1' }));
    expect(r).toMatchObject({ codigo: 'MEDIO_PAGO_INVALIDO', campo: 'medio_pago_id', message: 'El medio de pago elegido no existe.' });
  });
});
