import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { alcanceSucursalUsuario } from 'src/utils/alcance-sucursal';
import { NumeracionesLookupController } from './numeraciones-lookup.controller';
import { NumeracionesController } from './numeraciones.controller';
import { NumeracionesService } from './numeraciones.service';

jest.mock('src/utils/alcance-sucursal', () => ({
  ...jest.requireActual('src/utils/alcance-sucursal'),
  alcanceSucursalUsuario: jest.fn(),
}));
const alcanceMock = alcanceSucursalUsuario as jest.Mock;

/**
 * Aislamiento de `/numeraciones` (carril C, T1).
 * Toda ruta filtra por la empresa del token: una numeración, punto o sucursal de otra empresa responde 404 como si no
 * existiera y no se escribe nada. Dentro de la empresa, la sucursal tiene que estar en el alcance del usuario (403
 * `SUCURSAL_FUERA_DE_ALCANCE`), como en sucursales/facturas/compras. Alcance `null` (sin asignaciones o acceso elevado)
 * alcanza con que sea de la empresa: así no se corta a la emisión, POS ni la app móvil de quien no tiene asignaciones.
 */
const NUM = '11111111-1111-4111-8111-111111111111';
const EMP = '22222222-2222-4222-8222-222222222222';
const OTRA = '33333333-3333-4333-8333-333333333333';
const SUC = '44444444-4444-4444-8444-444444444444';
const SUC_B = '55555555-5555-4555-8555-555555555555';
const PUNTO = '66666666-6666-4666-8666-666666666666';
const TIMB = '77777777-7777-4777-8777-777777777777';

const FILA = { id: NUM, empresa_id: EMP, numero_actual: 1, numero_inicial: 1, numero_final: null, active: true, es_default: false };

/** Base "en memoria" mínima: solo existe la numeración NUM de EMP, en la sucursal SUC por el punto PUNTO. */
const crear = () => {
  const deEmp = (where: any) => where?.empresa_id === EMP;
  const escrituras = {
    update: jest.fn().mockResolvedValue(FILA),
    updateMany: jest.fn().mockResolvedValue({ count: 1 }),
    deleteMany: jest.fn().mockResolvedValue({ count: 1 }),
    create: jest.fn().mockResolvedValue({ ...FILA, tipo_documento: null }),
  };
  const numeraciones = {
    findFirst: jest.fn(({ where }: any) =>
      Promise.resolve(where?.id === NUM && deEmp(where) ? { ...FILA, punto_expedicion: { sucursal_id: SUC } } : where?.id ? null : null),
    ),
    findUnique: jest.fn().mockResolvedValue({ ...FILA, tipo_documento: null, punto_expedicion: null }),
    findMany: jest.fn().mockResolvedValue([FILA]),
    ...escrituras,
  };
  const tx: any = {
    $queryRaw: jest.fn((_s: unknown, ...vals: unknown[]) => Promise.resolve(vals.includes(NUM) && vals.includes(EMP) ? [FILA] : [])),
    numeraciones_documento: numeraciones,
    audit_logs: { create: jest.fn() },
    ...Object.fromEntries(
      ['sesion_caja_documentos', 'nota_remision_cab', 'solicitud_credito', 'factura_cab', 'nota_credito_cab', 'nota_debito_cab'].map((t) => [
        t,
        { count: jest.fn().mockResolvedValue(0) },
      ]),
    ),
  };
  const prisma: any = {
    ...tx,
    $transaction: jest.fn((arg: any) => (typeof arg === 'function' ? arg(tx) : Promise.all(arg))),
    empresas_sucursales: {
      findFirst: jest.fn(({ where }: any) => Promise.resolve([SUC, SUC_B].includes(where?.id) && deEmp(where) ? { id: where.id } : null)),
    },
    empresas_puntos_expedicion: {
      findFirst: jest.fn(({ where }: any) => Promise.resolve(where?.id === PUNTO && deEmp(where) ? { id: PUNTO, sucursal_id: SUC } : null)),
      findMany: jest.fn().mockResolvedValue([{ id: PUNTO, cajas: [] }]),
    },
    empresas_timbrado: {
      findFirst: jest.fn(({ where }: any) => Promise.resolve(where?.id === TIMB && deEmp(where) ? { id: TIMB } : null)),
    },
  };
  const audit = { log: jest.fn(), logEnTransaccion: jest.fn() };
  const service = new NumeracionesService(prisma, audit as any);
  const sinEscrituras = () => {
    for (const f of Object.values(escrituras)) expect(f).not.toHaveBeenCalled();
    expect(audit.log).not.toHaveBeenCalled();
    expect(audit.logEnTransaccion).not.toHaveBeenCalled();
  };
  return { service, prisma, tx, audit, sinEscrituras };
};

/** Cada ruta con `:id` del servicio, llamada sobre la numeración NUM con la empresa dada. */
const RUTAS_ID: Array<[string, (s: NumeracionesService, emp: string) => Promise<unknown>]> = [
  ['findOne (GET :id)', (s, e) => s.findOne(NUM, e, 'u')],
  ['getNextNumber (GET :id/next)', (s, e) => s.getNextNumber(NUM, e, 'u')],
  ['reserveNextNumber (POST :id/reserve)', (s, e) => s.reserveNextNumber(NUM, e, 'u')],
  ['incrementNumber (PUT :id/increment)', (s, e) => s.incrementNumber(NUM, e, 'u')],
  ['setDefault (PUT :id/set-default)', (s, e) => s.setDefault(NUM, e, 'u')],
  ['unsetDefault (PUT :id/unset-default)', (s, e) => s.unsetDefault(NUM, e, 'u')],
  ['toggleStatus (PUT activar-desactivar/:id)', (s, e) => s.toggleStatus(NUM, e, 'u')],
  ['update (PUT :id)', (s, e) => s.update(NUM, { numero_final: 50 }, e, 'u')],
  ['remove (DELETE :id)', (s, e) => s.remove(NUM, e, 'u')],
  ['ajustarCorrelativo (PATCH :id/correlativo)', (s, e) => s.ajustarCorrelativo(NUM, { numero_actual: 5, motivo: 'Salto por talonario perdido' }, e, 'u')],
];

beforeEach(() => alcanceMock.mockReset().mockResolvedValue(null));

describe('rutas con :id', () => {
  it.each(RUTAS_ID)('%s: numeración de otra empresa → 404 sin escribir', async (_n, llamar) => {
    const { service, sinEscrituras } = crear();
    await expect(llamar(service, OTRA)).rejects.toBeInstanceOf(NotFoundException);
    sinEscrituras();
  });

  it.each(RUTAS_ID)('%s: sucursal fuera del alcance del usuario → 403 sin escribir', async (_n, llamar) => {
    alcanceMock.mockResolvedValue({ sucursalIds: [SUC_B], puntosEstablecimiento: [], depositoIds: [] });
    const { service, sinEscrituras } = crear();
    await expect(llamar(service, EMP)).rejects.toBeInstanceOf(ForbiddenException);
    sinEscrituras();
  });

  it.each(RUTAS_ID)('%s: de la empresa y en el alcance → pasa', async (_n, llamar) => {
    alcanceMock.mockResolvedValue({ sucursalIds: [SUC], puntosEstablecimiento: [], depositoIds: [] });
    const { service } = crear();
    // la numeración FILA está sin usar (actual = inicial = 1): el ajuste a 5 y el borrado pasan
    await expect(llamar(service, EMP)).resolves.toBeDefined();
  });

  it('reserve y increment bloquean la fila filtrando por la empresa', async () => {
    const { service, tx } = crear();
    await service.reserveNextNumber(NUM, EMP, 'u');
    await service.incrementNumber(NUM, EMP, 'u');
    for (const c of tx.$queryRaw.mock.calls) {
      expect((c[0] as string[]).join('?')).toMatch(/empresa_id = \?::uuid[\s\S]*FOR UPDATE/);
      expect(c.slice(1)).toEqual(expect.arrayContaining([NUM, EMP]));
    }
    expect(tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM, empresa_id: EMP }, data: { numero_actual: 2 } });
  });
});

describe('listados y alta', () => {
  it.each([
    ['lookup operativo (soloActivos)', true],
    ['GET sucursal/:id (admin)', false],
  ])('%s: sucursal de otra empresa → 404; fuera del alcance → 403; en alcance filtra por empresa', async (_n, soloActivos) => {
    const a = crear();
    await expect(a.service.findAllBySucursal(SUC, OTRA, 'u', undefined, soloActivos)).rejects.toBeInstanceOf(NotFoundException);
    expect(a.prisma.empresas_puntos_expedicion.findMany).not.toHaveBeenCalled();

    alcanceMock.mockResolvedValue({ sucursalIds: [SUC_B], puntosEstablecimiento: [], depositoIds: [] });
    const b = crear();
    await expect(b.service.findAllBySucursal(SUC, EMP, 'u', undefined, soloActivos)).rejects.toBeInstanceOf(ForbiddenException);
    expect(b.prisma.empresas_puntos_expedicion.findMany).not.toHaveBeenCalled();

    alcanceMock.mockResolvedValue({ sucursalIds: [SUC], puntosEstablecimiento: [], depositoIds: [] });
    const c = crear();
    await c.service.findAllBySucursal(SUC, EMP, 'u', undefined, soloActivos);
    expect(c.prisma.empresas_puntos_expedicion.findMany).toHaveBeenCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ sucursal_id: SUC, empresa_id: EMP }) }),
    );
    expect(c.prisma.numeraciones_documento.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ empresa_id: EMP }) }));
  });

  it('lookup con alcance null (sin asignaciones / acceso elevado): pasa con una sucursal de la empresa', async () => {
    const { service, prisma } = crear();
    await service.findAllBySucursal(SUC, EMP, 'u', undefined, true);
    expect(prisma.numeraciones_documento.findMany).toHaveBeenCalled();
  });

  it('GET ?punto_expedicion_id: punto de otra empresa → 404; fuera del alcance → 403; propio filtra por empresa', async () => {
    const a = crear();
    await expect(a.service.findAllByPuntoExpedicion(PUNTO, OTRA, 'u')).rejects.toBeInstanceOf(NotFoundException);
    expect(a.prisma.numeraciones_documento.findMany).not.toHaveBeenCalled();

    alcanceMock.mockResolvedValue({ sucursalIds: [SUC_B], puntosEstablecimiento: [], depositoIds: [] });
    const b = crear();
    await expect(b.service.findAllByPuntoExpedicion(PUNTO, EMP, 'u')).rejects.toBeInstanceOf(ForbiddenException);

    alcanceMock.mockResolvedValue(null);
    const c = crear();
    await c.service.findAllByPuntoExpedicion(PUNTO, EMP, 'u');
    expect(c.prisma.numeraciones_documento.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { punto_expedicion_id: PUNTO, empresa_id: EMP } }));
  });

  it('POST: la empresa sale del token (no del cuerpo); punto o timbrado de otra empresa → 404 sin crear', async () => {
    const a = crear();
    await expect(
      a.service.create({ empresa_id: EMP, punto_expedicion_id: PUNTO, tipo_documento_id: 'td' }, OTRA, 'u'),
    ).rejects.toBeInstanceOf(NotFoundException);
    a.sinEscrituras();

    const b = crear();
    await expect(
      b.service.create({ empresa_id: EMP, punto_expedicion_id: PUNTO, tipo_documento_id: 'td', timbrado_id: '88888888-8888-4888-8888-888888888888' }, EMP, 'u'),
    ).rejects.toBeInstanceOf(NotFoundException);
    b.sinEscrituras();

    const c = crear();
    c.prisma.numeraciones_documento.findFirst.mockResolvedValue(null); // no existe la combinación
    await c.service.create({ empresa_id: OTRA, punto_expedicion_id: PUNTO, tipo_documento_id: 'td', timbrado_id: TIMB }, EMP, 'u');
    expect(c.prisma.numeraciones_documento.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ empresa_id: EMP }) }));
  });

  it('PUT con timbrado de otra empresa → 404 sin escribir', async () => {
    const { service, sinEscrituras } = crear();
    await expect(service.update(NUM, { timbrado_id: '88888888-8888-4888-8888-888888888888' }, EMP, 'u')).rejects.toBeInstanceOf(NotFoundException);
    sinEscrituras();
  });
});

describe('los controllers pasan la empresa y el usuario del token', () => {
  const user = { id: 'u1', empresa_id: 'e1' } as any;
  const servicio = () => new Proxy({} as Record<string, jest.Mock>, { get: (t, k: string) => (t[k] ??= jest.fn().mockResolvedValue({})) });

  it.each([
    ['create', (c: any) => c.create({ punto_expedicion_id: 'p' }, user), [{ punto_expedicion_id: 'p' }, 'e1', 'u1']],
    ['findAllByPuntoExpedicion', (c: any) => c.findAllByPuntoExpedicion('p', user), ['p', 'e1', 'u1']],
    ['findAllBySucursal', (c: any) => c.findAllBySucursal('s', user, 't'), ['s', 'e1', 'u1', 't']],
    ['findOne', (c: any) => c.findOne('n', user), ['n', 'e1', 'u1']],
    ['getNextNumber', (c: any) => c.getNextNumber('n', user), ['n', 'e1', 'u1']],
    ['reserveNextNumber', (c: any) => c.reserveNextNumber('n', user), ['n', 'e1', 'u1']],
    ['incrementNumber', (c: any) => c.incrementNumber('n', user), ['n', 'e1', 'u1']],
    ['setDefault', (c: any) => c.setDefault('n', user), ['n', 'e1', 'u1']],
    ['unsetDefault', (c: any) => c.unsetDefault('n', user), ['n', 'e1', 'u1']],
    ['toggleStatus', (c: any) => c.toggleStatus('n', user), ['n', 'e1', 'u1']],
  ] as const)('%s', async (m, llamar, args) => {
    const s = servicio();
    await llamar(new NumeracionesController(s as any));
    expect(s[m]).toHaveBeenCalledWith(...args);
  });

  it('lookup operativo: sucursal + empresa + usuario, solo activos', async () => {
    const s = servicio();
    await new NumeracionesLookupController(s as any).findAllBySucursal('s', user, 't');
    expect(s.findAllBySucursal).toHaveBeenCalledWith('s', 'e1', 'u1', 't', true);
  });
});
