import { FacturasService } from './facturas.service';
import { reservarNumeroFactura, resolverDepositoVenta } from './numeracion-venta';

jest.mock('../stock/tipos-movimiento-inventario', () => ({
  ...jest.requireActual('../stock/tipos-movimiento-inventario'),
  tipoMovimientoInventarioId: jest.fn().mockResolvedValue('tm-venta'),
}));

/**
 * Factura automática (`POST /facturas/automatico`), ola 5 de Existencias:
 *  - producto y cliente solo de la empresa del usuario (antes se buscaban por id solo: IDOR entre empresas);
 *  - número con la misma reserva atómica de la venta normal (numeración con FOR UPDATE), no `max + 1`;
 *  - depósito con la misma regla de la venta normal (el pedido o el principal de la sucursal del punto), nunca «el primero».
 */
const EMP_A = 'eA';
const EMP_B = 'eB';

function armar(opts: {
  productoEmpresa?: string;
  clienteEmpresa?: string;
  numeracion?: Record<string, unknown> | null;
  puntoSucursalId?: string | null;
  manejaInventario?: boolean;
} = {}) {
  const productoEmpresa = opts.productoEmpresa ?? EMP_A;
  const clienteEmpresa = opts.clienteEmpresa ?? EMP_A;
  const numeracion =
    opts.numeracion === undefined
      ? { id: 'num-1', numero_actual: 42, numero_final: null, active: true, punto_expedicion_id: 'pe-1', tipo_codigo: 1 }
      : opts.numeracion;
  const puntoSucursalId = opts.puntoSucursalId === undefined ? 'suc-2' : opts.puntoSucursalId;

  const db: any = {
    productos: {
      findFirst: jest.fn(async ({ where }: any) =>
        where.id === 'prod-1' && (where.empresa_id === undefined || where.empresa_id === productoEmpresa)
          ? { id: 'prod-1', empresa_id: productoEmpresa, maneja_inventario: opts.manejaInventario ?? true, maneja_lote: false, precio_costo: 100 }
          : null,
      ),
    },
    clientes: {
      findFirst: jest.fn(async ({ where }: any) =>
        where.id === 'cli-1' && (where.personas?.empresa_id === undefined || where.personas?.empresa_id === clienteEmpresa)
          ? { id: 'cli-1', persona_id: null, personas: {}, tipo_operacion: { codigo: 1 } }
          : null,
      ),
    },
    indicador_presencia: { findFirst: jest.fn().mockResolvedValue({ id: 'ip' }) },
    moneda: { findFirst: jest.fn().mockResolvedValue({ id: 'pyg', codigo: 'PYG' }) },
    condicion_operacion: { findFirst: jest.fn().mockResolvedValue({ id: 'co' }) },
    tipo_impuesto: { findFirst: jest.fn().mockResolvedValue({ id: 'ti' }) },
    tipo_transaccion: { findFirst: jest.fn().mockResolvedValue({ id: 'tt' }) },
    medio_pago: { findFirst: jest.fn().mockResolvedValue({ id: 'mp' }) },
    $queryRaw: jest.fn(async () => (numeracion ? [numeracion] : [])),
    empresas_puntos_expedicion: {
      findUnique: jest.fn().mockResolvedValue({
        id: 'pe-1',
        punto_expedicion: '002',
        caja_id: null,
        empresas_sucursales: puntoSucursalId ? { id: puntoSucursalId, punto_establecimiento: '003', config: null } : null,
      }),
    },
    numeraciones_documento: { update: jest.fn().mockResolvedValue({}) },
    depositos: {
      // Tres principales activos en la empresa: sin sucursal devolvería «el primero» (dep-1); la regla pide el de la sucursal.
      findFirst: jest.fn(async ({ where }: any) => {
        if (where.empresa_id !== EMP_A) return null;
        if (where.id) return where.id === 'dep-pedido' ? { id: 'dep-pedido', sucursal_id: 'suc-9' } : null;
        if (where.sucursal_id) return where.sucursal_id === 'suc-2' ? { id: 'dep-2', sucursal_id: 'suc-2' } : null;
        return { id: 'dep-1', sucursal_id: 'suc-1' };
      }),
    },
    factura_cab: {
      findFirst: jest.fn().mockResolvedValue({ dnumdoc: '0000007' }),
      create: jest.fn(async ({ data }: any) => ({ id: 'fc-1', ...data })),
    },
    factura_det: { create: jest.fn().mockResolvedValue({ id: 'fd-1' }) },
    factura_det_lote: { createMany: jest.fn() },
    factura_forma_pagos: { create: jest.fn() },
    factura_subtotales: { create: jest.fn() },
    stock_deposito: { upsert: jest.fn() },
    movimientos_inventario: { create: jest.fn() },
  };
  db.$transaction = jest.fn(async (fn: any) => fn(db));

  const service = Object.create(FacturasService.prototype) as any;
  service.prisma = db;
  service.planLimits = { checkLimit: jest.fn() };
  service.logger = { debug: jest.fn(), log: jest.fn(), error: jest.fn() };
  service.personasService = { validatePersonaById: jest.fn().mockResolvedValue([]) };
  service.lotesService = { isEnabledForEmpresa: jest.fn().mockResolvedValue(false), bloquearStockDe: jest.fn() };
  service.fifoService = { deductFifo: jest.fn() };
  service.auditService = { log: jest.fn() };
  return { service, db };
}

const dto = (cab: Record<string, unknown> = {}) =>
  ({
    cabecera: { cliente_id: 'cli-1', numeracion_id: 'num-1', ...cab },
    items: [{ producto_id: 'prod-1', descripcion: 'ZZ', cantidad: 2, precio_unitario: 1000 }],
  }) as any;

describe('FacturasService · factura automática', () => {
  it('IDOR: un producto de otra empresa responde 404 PRODUCTO_NO_ENCONTRADO y no crea nada', async () => {
    const { service, db } = armar({ productoEmpresa: EMP_B });
    await expect(service.createFacturaAutomatico(dto(), EMP_A, 'u1')).rejects.toMatchObject({
      status: 404,
      response: { codigo: 'PRODUCTO_NO_ENCONTRADO' },
    });
    expect(db.productos.findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ empresa_id: EMP_A }) }));
    expect(db.factura_cab.create).not.toHaveBeenCalled();
  });

  it('IDOR: un cliente de otra empresa responde 404 CLIENTE_NO_ENCONTRADO y no crea nada', async () => {
    const { service, db } = armar({ clienteEmpresa: EMP_B });
    await expect(service.createFacturaAutomatico(dto(), EMP_A, 'u1')).rejects.toMatchObject({
      status: 404,
      response: { codigo: 'CLIENTE_NO_ENCONTRADO' },
    });
    expect(db.factura_cab.create).not.toHaveBeenCalled();
  });

  it('sin numeración responde 400 NUMERACION_REQUERIDA', async () => {
    const { service, db } = armar();
    await expect(service.createFacturaAutomatico(dto({ numeracion_id: undefined }), EMP_A, 'u1')).rejects.toMatchObject({
      status: 400,
      response: { codigo: 'NUMERACION_REQUERIDA', campo: 'numeracion_id' },
    });
    expect(db.factura_cab.create).not.toHaveBeenCalled();
  });

  it('numeración de otra empresa (la consulta con FOR UPDATE filtra por empresa): 404 NUMERACION_NO_ENCONTRADA', async () => {
    const { service, db } = armar({ numeracion: null });
    await expect(service.createFacturaAutomatico(dto(), EMP_A, 'u1')).rejects.toMatchObject({
      status: 404,
      response: { codigo: 'NUMERACION_NO_ENCONTRADA' },
    });
    expect(db.factura_cab.create).not.toHaveBeenCalled();
  });

  it('una numeración que no es de factura responde 400 NUMERACION_NO_ES_FACTURA', async () => {
    const { service } = armar({
      numeracion: { id: 'num-1', numero_actual: 3, numero_final: null, active: true, punto_expedicion_id: 'pe-1', tipo_codigo: 500 },
    });
    await expect(service.createFacturaAutomatico(dto(), EMP_A, 'u1')).rejects.toMatchObject({
      status: 400,
      response: { codigo: 'NUMERACION_NO_ES_FACTURA' },
    });
  });

  it('numera con la reserva atómica de la numeración, en la misma transacción que la cabecera', async () => {
    const { service, db } = armar();
    const r = await service.createFacturaAutomatico(dto(), EMP_A, 'u1');
    const sql = (db.$queryRaw.mock.calls[0][0] as string[]).join('?');
    expect(sql).toMatch(/FOR UPDATE/);
    expect(sql).toMatch(/empresa_id/);
    expect(db.numeraciones_documento.update).toHaveBeenCalledWith({ where: { id: 'num-1' }, data: { numero_actual: 43 } });
    expect(db.factura_cab.create).toHaveBeenCalledWith(
      expect.objectContaining({ data: expect.objectContaining({ dest: '003', dpunexp: '002', dnumdoc: '0000042' }) }),
    );
    expect(db.factura_cab.findFirst).not.toHaveBeenCalled(); // nada de max + 1
    expect(r).toMatchObject({ numero: '003-002-0000042' });
  });

  it('depósito: el principal de la sucursal del punto de expedición, no el primero de la empresa', async () => {
    const { service, db } = armar();
    await service.createFacturaAutomatico(dto(), EMP_A, 'u1');
    expect(db.factura_det.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ deposito_id: 'dep-2' }) }));
    expect(db.stock_deposito.upsert).toHaveBeenCalledWith(
      expect.objectContaining({ where: { deposito_id_producto_id: { deposito_id: 'dep-2', producto_id: 'prod-1' } } }),
    );
  });

  it('depósito: el de la cabecera si es de la empresa y está activo', async () => {
    const { service, db } = armar();
    await service.createFacturaAutomatico(dto({ deposito_id: 'dep-pedido' }), EMP_A, 'u1');
    expect(db.factura_det.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ deposito_id: 'dep-pedido' }) }));
  });

  it('depósito: si el punto no tiene sucursal y no se manda depósito, 400 DEPOSITO_NO_DETERMINADO sin crear nada', async () => {
    const { service, db } = armar({ puntoSucursalId: null });
    await expect(service.createFacturaAutomatico(dto(), EMP_A, 'u1')).rejects.toMatchObject({
      status: 400,
      response: { codigo: 'DEPOSITO_NO_DETERMINADO' },
    });
    expect(db.factura_cab.create).not.toHaveBeenCalled();
  });

  it('un producto sin inventario no necesita depósito', async () => {
    const { service, db } = armar({ puntoSucursalId: null, manejaInventario: false });
    await service.createFacturaAutomatico(dto(), EMP_A, 'u1');
    expect(db.factura_det.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ deposito_id: null }) }));
    expect(db.stock_deposito.upsert).not.toHaveBeenCalled();
  });
});

describe('numeracion-venta', () => {
  it('reservarNumeroFactura bloquea la numeración de la empresa y suma uno', async () => {
    const tx: any = {
      $queryRaw: jest.fn().mockResolvedValue([{ id: 'n', numero_actual: 9, numero_final: 10, active: true, punto_expedicion_id: 'pe', tipo_codigo: 1 }]),
      empresas_puntos_expedicion: { findUnique: jest.fn().mockResolvedValue({ id: 'pe', punto_expedicion: '004', empresas_sucursales: { id: 's', punto_establecimiento: '001' } }) },
      numeraciones_documento: { update: jest.fn() },
    };
    const r = await reservarNumeroFactura(tx, { numeracionId: 'n', empresaId: EMP_A });
    expect(r).toMatchObject({ dnumdoc: '0000009', dest: '001', dpunexp: '004' });
    const [strings, ...valores] = tx.$queryRaw.mock.calls[0];
    expect(strings.join('?')).toMatch(/empresa_id = \?::uuid/);
    expect(valores).toEqual(['n', EMP_A]);
    expect(tx.numeraciones_documento.update).toHaveBeenCalledWith({ where: { id: 'n' }, data: { numero_actual: 10 } });
  });

  it('reservarNumeroFactura: número final alcanzado → 409', async () => {
    const tx: any = { $queryRaw: jest.fn().mockResolvedValue([{ id: 'n', numero_actual: 10, numero_final: 10, active: true, punto_expedicion_id: 'pe', tipo_codigo: 1 }]) };
    await expect(reservarNumeroFactura(tx, { numeracionId: 'n', empresaId: EMP_A })).rejects.toMatchObject({ status: 409 });
  });

  it('resolverDepositoVenta: el pedido manda; si no, el principal de la sucursal; sin sucursal, null', async () => {
    const tx: any = {
      depositos: {
        findFirst: jest.fn(async ({ where }: any) =>
          where.id === 'd-ped' ? { id: 'd-ped' } : where.sucursal_id === 's1' ? { id: 'd-s1' } : null,
        ),
      },
    };
    expect(await resolverDepositoVenta(tx, { empresaId: EMP_A, depositoId: 'd-ped', sucursalId: 's1' })).toMatchObject({ id: 'd-ped' });
    expect(await resolverDepositoVenta(tx, { empresaId: EMP_A, depositoId: null, sucursalId: 's1' })).toMatchObject({ id: 'd-s1' });
    expect(await resolverDepositoVenta(tx, { empresaId: EMP_A, depositoId: null, sucursalId: null })).toBeNull();
    for (const [args] of tx.depositos.findFirst.mock.calls) expect(args.where).toMatchObject({ empresa_id: EMP_A, active: true });
  });
});

describe('FacturasService · venta normal: productos de la empresa', () => {
  it('busca los productos de la factura solo en la empresa del usuario', async () => {
    const service = Object.create(FacturasService.prototype) as any;
    const findMany = jest.fn().mockResolvedValue([]);
    service.prisma = {
      factura_cab: { findFirst: jest.fn() },
      usuario: { findUnique: jest.fn() },
      perfiles_privilegios: { findFirst: jest.fn() },
      moneda: { findUnique: jest.fn().mockResolvedValue({ id: 'pyg', codigo: 'PYG' }) },
      condicion_operacion: { findUnique: jest.fn().mockResolvedValue({ id: 'co', codigo: 1 }) },
      productos: { findMany },
    };
    service.planLimits = { checkLimit: jest.fn() };
    service.logger = { error: jest.fn(), log: jest.fn() };
    service.clientesService = { findOne: jest.fn().mockResolvedValue({ data: { tipo_operacion: { descripcion: 'B2C' } } }) };
    service.personasService = { validatePersonaById: jest.fn().mockResolvedValue([]) };
    await expect(
      service.create(
        {
          cabecera: { cliente_id: 'c', numeracion_id: 'n', moneda_id: 'pyg', condicion_operacion_id: 'co' },
          items: [{ producto_id: 'p-otra', descripcion: 'X', cantidad: 1, precio_unitario: 1 }],
          pagos: [{ medio_pago_id: 'm' }],
          subtotal: {},
        },
        EMP_A,
        'u1',
      ),
    ).rejects.toMatchObject({ status: 404 });
    expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ empresa_id: EMP_A }) }));
  });
});
