import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { AjustarCorrelativoDto } from './dto/ajustar-correlativo.dto';
import { NumeracionesService } from './numeraciones.service';

jest.mock('src/utils/alcance-sucursal', () => ({
  ...jest.requireActual('src/utils/alcance-sucursal'),
  alcanceSucursalUsuario: jest.fn().mockResolvedValue(null),
}));

/**
 * Correlativo fiscal de una numeración (carril C, T1).
 *
 * `numero_actual` es el PRÓXIMO número a emitir. Nunca baja ni se repite: solo se ajusta hacia adelante con
 * `PATCH :id/correlativo` (motivo obligatorio, auditado), bajo el mismo bloqueo de fila (`FOR UPDATE`) que usa la emisión,
 * así un ajuste y una factura a la vez no se pisan. `PUT :id` ya no lo cambia; `numero_inicial` no cambia si la numeración
 * está usada (`numero_actual > numero_inicial`) y `numero_final` no queda por debajo de `numero_actual`.
 */
const NUM_ID = '11111111-1111-4111-8111-111111111111';
const EMP = '22222222-2222-4222-8222-222222222222';
const OTRA_EMP = '33333333-3333-4333-8333-333333333333';
const SUC = '44444444-4444-4444-8444-444444444444';

const fila = (over: Record<string, unknown> = {}) => ({
  id: NUM_ID,
  empresa_id: EMP,
  numero_actual: 15,
  numero_inicial: 1,
  numero_final: null as number | null,
  active: true,
  timbrado_id: null as string | null,
  ...over,
});

const crear = (filaBloqueada: ReturnType<typeof fila> | null = fila()) => {
  const tx: any = {
    $queryRaw: jest.fn().mockResolvedValue(filaBloqueada ? [filaBloqueada] : []),
    numeraciones_documento: {
      updateMany: jest.fn().mockResolvedValue({ count: 1 }),
      findUnique: jest.fn().mockImplementation(() => Promise.resolve({ ...filaBloqueada, tipo_documento: {}, timbrado: null })),
      deleteMany: jest.fn().mockResolvedValue({ count: 1 }),
    },
    sesion_caja_documentos: { count: jest.fn().mockResolvedValue(0) },
    nota_remision_cab: { count: jest.fn().mockResolvedValue(0) },
    solicitud_credito: { count: jest.fn().mockResolvedValue(0) },
    factura_cab: { count: jest.fn().mockResolvedValue(0) },
    nota_credito_cab: { count: jest.fn().mockResolvedValue(0) },
    nota_debito_cab: { count: jest.fn().mockResolvedValue(0) },
  };
  // `exigirNumeracion` (antes de la transacción): la numeración de la empresa del token y su sucursal.
  const prisma: any = {
    $transaction: jest.fn((cb: (t: unknown) => unknown) => cb(tx)),
    numeraciones_documento: {
      findFirst: jest.fn().mockResolvedValue(filaBloqueada ? { id: NUM_ID, punto_expedicion: { sucursal_id: SUC } } : null),
    },
    empresas_sucursales: { findFirst: jest.fn().mockResolvedValue({ id: SUC }) },
  };
  const audit = { log: jest.fn().mockResolvedValue(undefined), logEnTransaccion: jest.fn().mockResolvedValue(undefined) };
  const service = new NumeracionesService(prisma, audit as any);
  /** valores interpolados en el SELECT ... FOR UPDATE */
  const valoresDelBloqueo = () => tx.$queryRaw.mock.calls[0].slice(1);
  const sqlDelBloqueo = () => (tx.$queryRaw.mock.calls[0][0] as string[]).join('?');
  return { service, prisma, tx, audit, valoresDelBloqueo, sqlDelBloqueo };
};

const codigo = async (p: Promise<unknown>) => {
  try {
    await p;
  } catch (e: any) {
    return { tipo: e.constructor, codigo: e.getResponse?.()?.codigo };
  }
  throw new Error('no lanzó');
};

describe('PATCH /numeraciones/:id/correlativo', () => {
  it('ajusta 15 → 20 con motivo y audita anterior, nuevo y motivo en la misma transacción', async () => {
    const { service, tx, audit, valoresDelBloqueo, sqlDelBloqueo } = crear();
    tx.numeraciones_documento.findUnique.mockResolvedValue({ ...fila({ numero_actual: 20 }), tipo_documento: {}, timbrado: null });

    const res = await service.ajustarCorrelativo(NUM_ID, { numero_actual: 20, motivo: 'Salto por talonario perdido' }, EMP, 'user-1');

    expect(sqlDelBloqueo()).toMatch(/FOR UPDATE/);
    expect(valoresDelBloqueo()).toEqual(expect.arrayContaining([NUM_ID, EMP]));
    expect(tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_actual: 20 } });
    expect(audit.logEnTransaccion).toHaveBeenCalledWith(
      tx,
      expect.objectContaining({
        empresa_id: EMP,
        user_id: 'user-1',
        action: 'AJUSTE_CORRELATIVO',
        entity_id: NUM_ID,
        old_value: { numero_actual: 15 },
        new_value: { numero_actual: 20, motivo: 'Salto por talonario perdido' },
      }),
    );
    expect(audit.log).not.toHaveBeenCalled();
    expect(res).toEqual({ message: expect.any(String), data: expect.objectContaining({ id: NUM_ID, numero_actual: 20 }) });
  });

  it.each([15, 10])('15 → %i: 409 CORRELATIVO_HACIA_ATRAS sin escribir', async (nuevo) => {
    const { service, tx, audit } = crear();
    const r = await codigo(service.ajustarCorrelativo(NUM_ID, { numero_actual: nuevo, motivo: 'Salto por talonario perdido' }, EMP, 'u'));
    expect(r).toEqual({ tipo: ConflictException, codigo: 'CORRELATIVO_HACIA_ATRAS' });
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
    expect(audit.logEnTransaccion).not.toHaveBeenCalled();
  });

  it('final 100: hasta 99 se puede; 100 y 101 dan 409 CORRELATIVO_FUERA_DE_RANGO (la emisión corta con actual >= final)', async () => {
    const a = crear(fila({ numero_final: 100 }));
    await a.service.ajustarCorrelativo(NUM_ID, { numero_actual: 99, motivo: 'Salto por talonario perdido' }, EMP, 'u');
    expect(a.tx.numeraciones_documento.updateMany).toHaveBeenCalled();

    for (const n of [100, 101]) {
      const b = crear(fila({ numero_final: 100 }));
      const r = await codigo(b.service.ajustarCorrelativo(NUM_ID, { numero_actual: n, motivo: 'Salto por talonario perdido' }, EMP, 'u'));
      expect(r).toEqual({ tipo: ConflictException, codigo: 'CORRELATIVO_FUERA_DE_RANGO' });
      expect(b.tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
    }
  });

  it('numeración de otra empresa: 404 sin escribir (se busca por id + empresa del token)', async () => {
    const { service, prisma, tx, audit } = crear(null);
    const r = await codigo(service.ajustarCorrelativo(NUM_ID, { numero_actual: 20, motivo: 'Salto por talonario perdido' }, OTRA_EMP, 'u'));
    expect(r.tipo).toBe(NotFoundException);
    expect(prisma.numeraciones_documento.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { id: NUM_ID, empresa_id: OTRA_EMP } }));
    expect(prisma.$transaction).not.toHaveBeenCalled();
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
    expect(audit.logEnTransaccion).not.toHaveBeenCalled();
  });

  it('motivo de puros espacios: 400 MOTIVO_REQUERIDO sin consultar; se guarda recortado', async () => {
    const a = crear();
    const r = await codigo(a.service.ajustarCorrelativo(NUM_ID, { numero_actual: 20, motivo: '            ' }, EMP, 'u'));
    expect(r).toEqual({ tipo: BadRequestException, codigo: 'MOTIVO_REQUERIDO' });
    expect(a.prisma.$transaction).not.toHaveBeenCalled();

    const b = crear();
    await b.service.ajustarCorrelativo(NUM_ID, { numero_actual: 20, motivo: '  Salto por talonario perdido  ' }, EMP, 'u');
    expect(b.audit.logEnTransaccion).toHaveBeenCalledWith(b.tx, expect.objectContaining({ new_value: { numero_actual: 20, motivo: 'Salto por talonario perdido' } }));
  });

  it('id que no es UUID: 404 sin consultar', async () => {
    const { service, prisma } = crear();
    const r = await codigo(service.ajustarCorrelativo('no-uuid', { numero_actual: 20, motivo: 'Salto por talonario perdido' }, EMP, 'u'));
    expect(r.tipo).toBe(NotFoundException);
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });
});

describe('AjustarCorrelativoDto', () => {
  const errores = async (body: object) => (await validate(plainToInstance(AjustarCorrelativoDto, body))).map((e) => e.property);

  it('acepta número entero ≥ 1 y motivo de 10 a 500 caracteres', async () => {
    expect(await errores({ numero_actual: 20, motivo: 'Salto por talonario perdido' })).toEqual([]);
  });
  it('motivo de 5 caracteres → error (400 por el ValidationPipe)', async () => {
    expect(await errores({ numero_actual: 20, motivo: 'corto' })).toEqual(['motivo']);
  });
  it('sin motivo, o de más de 500 → error', async () => {
    expect(await errores({ numero_actual: 20 })).toEqual(['motivo']);
    expect(await errores({ numero_actual: 20, motivo: 'x'.repeat(501) })).toEqual(['motivo']);
  });
  it.each([0, -3, 2.5, '20'])('numero_actual %p → error', async (n) => {
    expect(await errores({ numero_actual: n, motivo: 'Salto por talonario perdido' })).toEqual(['numero_actual']);
  });
});

describe('PUT /numeraciones/:id', () => {
  it('numero_actual distinto al guardado → 400 USAR_AJUSTE_CORRELATIVO y sin escribir', async () => {
    const { service, tx, audit } = crear();
    const r = await codigo(service.update(NUM_ID, { numero_actual: 20, numero_final: 500 }, EMP, 'u'));
    expect(r).toEqual({ tipo: BadRequestException, codigo: 'USAR_AJUSTE_CORRELATIVO' });
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
    expect(audit.logEnTransaccion).not.toHaveBeenCalled();
  });

  it('mismo numero_actual y numero_final nuevo → 200; solo escribe numero_final', async () => {
    const { service, tx, audit, valoresDelBloqueo, sqlDelBloqueo } = crear();
    tx.numeraciones_documento.findUnique.mockResolvedValue({ ...fila({ numero_final: 500 }), tipo_documento: {}, timbrado: null });

    const res = await service.update(NUM_ID, { numero_actual: 15, numero_final: 500 }, EMP, 'u');

    expect(sqlDelBloqueo()).toMatch(/FOR UPDATE/);
    expect(valoresDelBloqueo()).toEqual(expect.arrayContaining([NUM_ID, EMP]));
    expect(tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_final: 500 } });
    expect(audit.logEnTransaccion).toHaveBeenCalledWith(tx, expect.objectContaining({ action: 'UPDATE', entity_id: NUM_ID }));
    expect(res).toEqual({ message: expect.any(String), data: expect.objectContaining({ numero_final: 500 }) });
  });

  it('campos fuera de la lista no llegan a la base', async () => {
    const { service, tx } = crear();
    await service.update(NUM_ID, { numero_final: 500, empresa_id: OTRA_EMP } as any, EMP, 'u');
    expect(tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_final: 500 } });
  });

  it('numero_inicial cambiado con la numeración usada (actual 15 > inicial 1) → 409 NUMERACION_USADA', async () => {
    const { service, tx } = crear();
    const r = await codigo(service.update(NUM_ID, { numero_inicial: 5 }, EMP, 'u'));
    expect(r).toEqual({ tipo: ConflictException, codigo: 'NUMERACION_USADA' });
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
  });

  it('numero_inicial igual al guardado con la numeración usada → pasa', async () => {
    const { service, tx } = crear();
    await service.update(NUM_ID, { numero_inicial: 1, numero_final: 500 }, EMP, 'u');
    expect(tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_final: 500 } });
  });

  it('numero_inicial cambiado sin usar: el próximo número arranca en el nuevo inicial', async () => {
    const { service, tx } = crear(fila({ numero_actual: 1, numero_inicial: 1 }));
    await service.update(NUM_ID, { numero_inicial: 51 }, EMP, 'u');
    expect(tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({
      where: { id: NUM_ID, empresa_id: EMP },
      data: { numero_inicial: 51, numero_actual: 51 },
    });
  });

  it('numero_inicial nuevo (sin usar) por encima del final guardado → 400 sin escribir', async () => {
    const { service, tx } = crear(fila({ numero_actual: 1, numero_inicial: 1, numero_final: 50 }));
    const r = await codigo(service.update(NUM_ID, { numero_inicial: 51 }, EMP, 'u'));
    expect(r.codigo).toBe('NUMERO_FINAL_MENOR_AL_ACTUAL');
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
  });

  it('caso NC real: inicial = actual = 12 y se baja el inicial a 1 → 409 INICIAL_MENOR_AL_ACTUAL; el actual no baja', async () => {
    const { service, tx } = crear(fila({ numero_actual: 12, numero_inicial: 12 }));
    const r = await codigo(service.update(NUM_ID, { numero_actual: 12, numero_inicial: 1 }, EMP, 'u'));
    expect(r).toEqual({ tipo: ConflictException, codigo: 'INICIAL_MENOR_AL_ACTUAL' });
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
  });

  it('timbrado: cambiarlo en una numeración usada → 409 NUMERACION_USADA; reenviar el mismo pasa; sin usar se cambia', async () => {
    const T1 = '55555555-5555-4555-8555-555555555551';
    const T2 = '55555555-5555-4555-8555-555555555552';
    const a = crear(fila({ timbrado_id: T1 }));
    a.prisma.empresas_timbrado = { findFirst: jest.fn().mockResolvedValue({ id: T2 }) };
    const r = await codigo(a.service.update(NUM_ID, { timbrado_id: T2 }, EMP, 'u'));
    expect(r).toEqual({ tipo: ConflictException, codigo: 'NUMERACION_USADA' });
    expect(a.tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();

    const b = crear(fila({ timbrado_id: T1 }));
    b.prisma.empresas_timbrado = { findFirst: jest.fn().mockResolvedValue({ id: T1 }) };
    await b.service.update(NUM_ID, { timbrado_id: T1, numero_final: 500 }, EMP, 'u');
    expect(b.tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_final: 500 } });

    const c = crear(fila({ numero_actual: 1, numero_inicial: 1, timbrado_id: T1 }));
    c.prisma.empresas_timbrado = { findFirst: jest.fn().mockResolvedValue({ id: T2 }) };
    await c.service.update(NUM_ID, { timbrado_id: T2 }, EMP, 'u');
    expect(c.tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { timbrado_id: T2 } });
  });

  it('numero_final menor a numero_actual → 400 y sin escribir', async () => {
    const { service, tx } = crear();
    const r = await codigo(service.update(NUM_ID, { numero_final: 14 }, EMP, 'u'));
    expect(r.tipo).toBe(BadRequestException);
    expect(r.codigo).toBe('NUMERO_FINAL_MENOR_AL_ACTUAL');
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
  });

  it('numero_final igual al próximo número → 400 (la agotaría); mayor pasa; reenviar el final guardado de una agotada pasa; null quita el tope', async () => {
    const a = crear();
    const r = await codigo(a.service.update(NUM_ID, { numero_final: 15 }, EMP, 'u'));
    expect(r.codigo).toBe('NUMERO_FINAL_MENOR_AL_ACTUAL');
    expect(a.tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
    const a2 = crear();
    await a2.service.update(NUM_ID, { numero_final: 16 }, EMP, 'u');
    expect(a2.tx.numeraciones_documento.updateMany).toHaveBeenCalled();
    const agotada = crear(fila({ numero_final: 15 }));
    await agotada.service.update(NUM_ID, { numero_actual: 15, numero_inicial: 1, numero_final: 15, active: false }, EMP, 'u');
    expect(agotada.tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_final: 15, active: false } });
    const b = crear(fila({ numero_final: 100 }));
    await b.service.update(NUM_ID, { numero_final: null } as any, EMP, 'u');
    expect(b.tx.numeraciones_documento.updateMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP }, data: { numero_final: null } });
  });

  it('numeración de otra empresa → 404 sin escribir', async () => {
    const { service, tx } = crear(null);
    const r = await codigo(service.update(NUM_ID, { numero_final: 500 }, OTRA_EMP, 'u'));
    expect(r.tipo).toBe(NotFoundException);
    expect(tx.numeraciones_documento.updateMany).not.toHaveBeenCalled();
  });
});

describe('DELETE /numeraciones/:id', () => {
  /** La numeración vista por `documentosDeNumeracion`: tipo y establecimiento-punto. */
  const conTipo = (tx: any, codigo: number) =>
    tx.numeraciones_documento.findUnique.mockResolvedValue({
      ...fila(),
      tipo_documento: { codigo },
      punto_expedicion: { punto_expedicion: '002', empresas_sucursales: { punto_establecimiento: '001' } },
    });

  it('caso NC real: inicial = actual = 12 pero con NC emitidas en su establecimiento-punto → 409 NUMERACION_CON_DOCUMENTOS sin borrar', async () => {
    const { service, tx, audit } = crear(fila({ numero_actual: 12, numero_inicial: 12 }));
    conTipo(tx, 5);
    tx.nota_credito_cab.count.mockResolvedValue(11);
    const r = await codigo(service.remove(NUM_ID, EMP, 'u'));
    expect(r).toEqual({ tipo: ConflictException, codigo: 'NUMERACION_CON_DOCUMENTOS' });
    expect(tx.nota_credito_cab.count).toHaveBeenCalledWith({ where: { empresa_id: EMP, dest: '001', dpunexp: '002' } });
    expect(tx.factura_cab.count).not.toHaveBeenCalled(); // solo la tabla de su tipo
    expect(tx.numeraciones_documento.deleteMany).not.toHaveBeenCalled();
    expect(audit.logEnTransaccion).not.toHaveBeenCalled();
  });

  it.each([
    ['factura en su establecimiento-punto', 1, 'factura_cab'],
    ['nota de débito', 6, 'nota_debito_cab'],
    ['documento de caja con su numeracion_id', 100, 'sesion_caja_documentos'],
    ['solicitud de crédito con su numeracion_id', 300, 'solicitud_credito'],
    ['remisión', 7, 'nota_remision_cab'],
  ])('sin usar pero con %s → 409 NUMERACION_CON_DOCUMENTOS', async (_n, tipo, tabla) => {
    const { service, tx } = crear(fila({ numero_actual: 1, numero_inicial: 1 }));
    conTipo(tx, tipo as number);
    tx[tabla as string].count.mockResolvedValue(1);
    const r = await codigo(service.remove(NUM_ID, EMP, 'u'));
    expect(r.codigo).toBe('NUMERACION_CON_DOCUMENTOS');
    expect(tx.numeraciones_documento.deleteMany).not.toHaveBeenCalled();
  });

  it('usada (actual 15 > inicial 1) → 409 NUMERACION_USADA sin borrar', async () => {
    const { service, tx, audit } = crear();
    const r = await codigo(service.remove(NUM_ID, EMP, 'u'));
    expect(r).toEqual({ tipo: ConflictException, codigo: 'NUMERACION_USADA' });
    expect(tx.numeraciones_documento.deleteMany).not.toHaveBeenCalled();
    expect(audit.logEnTransaccion).not.toHaveBeenCalled();
  });

  it('sin usar → 200, borra con la empresa en el filtro y audita', async () => {
    const { service, tx, audit, sqlDelBloqueo } = crear(fila({ numero_actual: 1, numero_inicial: 1 }));
    const res = await service.remove(NUM_ID, EMP, 'u');
    expect(sqlDelBloqueo()).toMatch(/FOR UPDATE/);
    expect(tx.numeraciones_documento.deleteMany).toHaveBeenCalledWith({ where: { id: NUM_ID, empresa_id: EMP } });
    expect(audit.logEnTransaccion).toHaveBeenCalledWith(tx, expect.objectContaining({ action: 'DELETE', entity_id: NUM_ID }));
    expect(res).toEqual({ message: expect.any(String) });
  });

  it('de otra empresa → 404 sin borrar', async () => {
    const { service, tx } = crear(null);
    const r = await codigo(service.remove(NUM_ID, OTRA_EMP, 'u'));
    expect(r.tipo).toBe(NotFoundException);
    expect(tx.numeraciones_documento.deleteMany).not.toHaveBeenCalled();
  });
});
