import { revertirPresupuestoPorAnulacionFactura } from './reversion-presupuesto-anulacion';

const EMPRESA = 'emp-1';
const FACTURA = 'fac-1';

function crearDb(opts: { factura: Record<string, any>; orden?: Record<string, any> | null; presupuestos: Array<Record<string, any>> }) {
  const historial: any[] = [];
  const coincide = (p: any, where: any) =>
    (where.id === undefined || p.id === where.id) &&
    (where.estado === undefined || p.estado === where.estado) &&
    (where.pedido_id === undefined || p.pedido_id === where.pedido_id) &&
    p.empresa_id === where.empresa_id &&
    (!where.OR || where.OR.some((c: any) => (c.id ? p.id === c.id : p.factura_id === c.factura_id)));
  const tx: any = {
    factura_cab: { findFirst: jest.fn(async () => opts.factura) },
    pedidos: { findFirst: jest.fn(async ({ where }: any) => (opts.orden && opts.orden.id === where.id ? opts.orden : null)) },
    presupuesto_cab: {
      findFirst: jest.fn(async ({ where }: any) => opts.presupuestos.find((p) => coincide(p, where)) ?? null),
      update: jest.fn(async ({ where, data }: any) => Object.assign(opts.presupuestos.find((p) => p.id === where.id)!, data)),
    },
    presupuesto_historial: { create: jest.fn(async ({ data }: any) => historial.push(data)) },
  };
  return { db: { $transaction: (fn: any) => fn(tx) } as any, historial, tx };
}

const FACTURA_CAB = { pedido_id: 'ov-1', presupuesto_id: null, dest: '001', dpunexp: '001', dnumdoc: '0000030' };

describe('Anular la factura devuelve el presupuesto', () => {
  it('vía orden de venta: la orden ya no está facturada → presupuesto vuelve a CONVERTED', async () => {
    const pres = { id: 'p-1', numero: 'P-0001', empresa_id: EMPRESA, estado: 'FACTURADO', pedido_id: 'ov-1', factura_id: null };
    const { db, historial } = crearDb({
      factura: FACTURA_CAB,
      orden: { id: 'ov-1', presupuesto_id: 'p-1', estado_orden: 'aprobada', numero_pedido: 'OV-7' },
      presupuestos: [pres],
    });
    const r = await revertirPresupuestoPorAnulacionFactura(db, FACTURA, EMPRESA);
    expect(r).toMatchObject({ revertido: true, estadoNuevo: 'CONVERTED', numero: 'P-0001' });
    expect(pres.estado).toBe('CONVERTED');
    expect(historial[0]).toMatchObject({ estado_anterior: 'FACTURADO', estado_nuevo: 'CONVERTED' });
    expect(historial[0].comentario).toContain('001-001-0000030');
  });

  it('idempotente: una segunda pasada no hace nada', async () => {
    const pres = { id: 'p-1', numero: 'P-0001', empresa_id: EMPRESA, estado: 'FACTURADO', pedido_id: 'ov-1', factura_id: null };
    const { db, historial } = crearDb({
      factura: FACTURA_CAB,
      orden: { id: 'ov-1', presupuesto_id: 'p-1', estado_orden: 'facturada_parcial', numero_pedido: null },
      presupuestos: [pres],
    });
    await revertirPresupuestoPorAnulacionFactura(db, FACTURA, EMPRESA);
    const r2 = await revertirPresupuestoPorAnulacionFactura(db, FACTURA, EMPRESA);
    expect(r2).toEqual({ revertido: false });
    expect(historial).toHaveLength(1);
  });

  it('si la orden sigue facturada entera, el presupuesto no se toca', async () => {
    const pres = { id: 'p-1', numero: 'P-0001', empresa_id: EMPRESA, estado: 'FACTURADO', pedido_id: 'ov-1', factura_id: null };
    const { db } = crearDb({
      factura: FACTURA_CAB,
      orden: { id: 'ov-1', presupuesto_id: 'p-1', estado_orden: 'facturada', numero_pedido: null },
      presupuestos: [pres],
    });
    expect(await revertirPresupuestoPorAnulacionFactura(db, FACTURA, EMPRESA)).toEqual({ revertido: false });
    expect(pres.estado).toBe('FACTURADO');
  });

  it('facturado directo (sin orden): vuelve a ACCEPTED y suelta la factura', async () => {
    const pres = { id: 'p-2', numero: 'P-0002', empresa_id: EMPRESA, estado: 'FACTURADO', pedido_id: null, factura_id: FACTURA };
    const { db } = crearDb({ factura: { ...FACTURA_CAB, pedido_id: null, presupuesto_id: 'p-2' }, presupuestos: [pres] });
    const r = await revertirPresupuestoPorAnulacionFactura(db, FACTURA, EMPRESA);
    expect(r).toMatchObject({ revertido: true, estadoNuevo: 'ACCEPTED' });
    expect(pres).toMatchObject({ estado: 'ACCEPTED', factura_id: null });
  });

  it('factura sin presupuesto ni orden: nada', async () => {
    const { db } = crearDb({ factura: { ...FACTURA_CAB, pedido_id: null }, presupuestos: [] });
    expect(await revertirPresupuestoPorAnulacionFactura(db, FACTURA, EMPRESA)).toEqual({ revertido: false });
  });
});
