import { crearServicio, EMPRESA, filaOferta, ID, REF, SUC } from './ofertas-test-utils';

/** B5: cada ruta por id busca dentro de la empresa; un id ajeno se ve igual que uno inexistente. */
describe('Ofertas: alcance por empresa (B5)', () => {
  const llamadas: [string, (s: any, id: string, empresa: string) => Promise<unknown>][] = [
    ['findOne', (s, id, e) => s.findOne(id, e)],
    ['getUsos', (s, id, e) => s.getUsos(id, e)],
    ['update', (s, id, e) => s.update(id, { nombre: 'X' }, e, 'u1')],
    ['toggleActive', (s, id, e) => s.toggleActive(id, e, 'u1')],
    ['remove', (s, id, e) => s.remove(id, e, 'u1')],
  ];

  it.each(llamadas)('%s: id de otra empresa → 404 OFERTA_NO_ENCONTRADA y no escribe', async (_, llamar) => {
    const { service, prisma, tx, cache } = crearServicio();
    await expect(llamar(service, ID, 'otra-empresa')).rejects.toMatchObject({ status: 404, response: { codigo: 'OFERTA_NO_ENCONTRADA' } });
    expect(prisma.ofertas.update).not.toHaveBeenCalled();
    expect(tx.ofertas.update).not.toHaveBeenCalled();
    expect(prisma.oferta_usos.findMany).not.toHaveBeenCalled();
    expect(cache.set).not.toHaveBeenCalled();
  });

  it.each(llamadas)('%s: id "abc" → el mismo 404 sin consultar', async (_, llamar) => {
    const { service, prisma } = crearServicio();
    await expect(llamar(service, 'abc', EMPRESA)).rejects.toMatchObject({ status: 404, response: { codigo: 'OFERTA_NO_ENCONTRADA' } });
    expect(prisma.ofertas.findFirst).not.toHaveBeenCalled();
  });

  it.each(llamadas)('%s: findFirst con { id, empresa_id }', async (_, llamar) => {
    const { service, prisma } = crearServicio();
    await llamar(service, ID, EMPRESA);
    expect(prisma.ofertas.findFirst.mock.calls[0][0].where).toEqual({ id: ID, empresa_id: EMPRESA });
  });

  const ALTA = { nombre: 'Promo', tipo: 'descuento_porcentaje', valor: 10, fecha_inicio: '2026-11-05T11:00:00.000Z', fecha_fin: '2026-11-30T11:00:00.000Z' };
  const escrituras: [string, (s: any, dto: any) => Promise<unknown>][] = [
    ['create', (s, dto) => s.create({ ...ALTA, ...dto }, EMPRESA, 'u1')],
    ['update', (s, dto) => s.update(ID, dto, EMPRESA, 'u1')],
  ];

  it.each(escrituras)('%s: sucursal ajena → 400 SUCURSAL_INVALIDA', async (_, escribir) => {
    const { service, prisma } = crearServicio();
    prisma.empresas_sucursales.count.mockResolvedValue(0);
    await expect(escribir(service, { sucursal_ids: [SUC] })).rejects.toMatchObject({ status: 400, response: { codigo: 'SUCURSAL_INVALIDA', campo: 'sucursal_ids' } });
    expect(prisma.empresas_sucursales.count.mock.calls[0][0].where).toEqual({ id: { in: [SUC] }, empresa_id: EMPRESA });
    expect(prisma.ofertas.create).not.toHaveBeenCalled();
  });

  it.each(escrituras.flatMap(([n, f]) => (['producto', 'categoria', 'marca'] as const).map((t) => [n, t, f] as const)))('%s: %s ajena → 400 REFERENCIA_INVALIDA', async (_, tipo, escribir) => {
    const { service, prisma } = crearServicio();
    const tabla = { producto: 'productos', categoria: 'categorias', marca: 'marcas' }[tipo];
    prisma[tabla].count.mockResolvedValue(0);
    await expect(escribir(service, { aplicaciones: [{ aplica_a: tipo, referencia_id: REF }] })).rejects.toMatchObject({ status: 400, response: { codigo: 'REFERENCIA_INVALIDA', campo: 'referencia_id' } });
    expect(prisma[tabla].count.mock.calls[0][0].where).toEqual({ id: { in: [REF] }, empresa_id: EMPRESA });
  });

  it('evaluar: un producto ajeno sale sin oferta (findMany con empresa_id)', async () => {
    const { service, prisma } = crearServicio();
    jest.spyOn(service, 'getOfertasActivas').mockResolvedValue([filaOferta()] as any);
    prisma.productos.findMany.mockResolvedValue([]);
    const r = await service.evaluarOfertas({ items: [{ producto_id: REF, cantidad: 1, precio_unitario: 100 }] } as any, EMPRESA);
    expect(prisma.productos.findMany.mock.calls[0][0].where).toEqual({ id: { in: [REF] }, empresa_id: EMPRESA });
    expect(r.items[0]).toMatchObject({ oferta_id: null, precio_final: 100 });
  });
});
