import { MiddlewareSifenService } from './middleware-sifen.service';

/**
 * Formato real de POST /api/maintenance para consultar un evento (captura del
 * middleware de producción, 2026-09-16): el payload lleva iTiDE y para EINU la
 * clave de la respuesta es "dEst-dPunExp-dNumIn/dNumFin", no "dEst-dPunExp-dNumDoc".
 */
describe('MiddlewareSifenService.consultarEventoEnMiddleware', () => {
  const service = Object.create(MiddlewareSifenService.prototype) as any;
  const EINU = { cdc: null, dest: '001', dpunexp: '001', dnumdoc: '0002339', evento_aplicado: 'EINU' };
  const ECAN = { cdc: '01801645506001001000100512026041216710145362', dest: '001', dpunexp: '001', dnumdoc: '0001005', evento_aplicado: 'ECAN' };
  const REGISTRO = {
    fecha_envio: null,
    fecha_firma: '01-09-2026 09:46:09',
    estado_evento: 'Documento Firmado',
    retorno_sifen: { estado: null, mensaje: null, protocolo: null, codrespuesta: null, fecha_retorno: null },
    fecha_registro: '01-09-2026 09:46:09',
  };
  let fetchMock: jest.Mock;
  beforeEach(() => {
    fetchMock = jest.fn().mockResolvedValue({ status: 200, json: async () => ({ status: 'success', response: {} }) });
    global.fetch = fetchMock as any;
  });
  const payloadEnviado = () => JSON.parse(fetchMock.mock.calls[0][1].body);

  it('EINU: va por rango de numeración, con iTiDE del tipo de documento y sin cdc', async () => {
    await service.consultarEventoEnMiddleware('http://mw', 'tok', EINU, 1);
    expect(payloadEnviado()).toEqual({
      tipOpe: '2',
      tipo: 'evento',
      fecha_inicial: null,
      fecha_final: null,
      nro_lote: null,
      iTiDE: 1,
      dEst: '001',
      dPunExp: '001',
      dNumIn: '0002339',
      dNumFin: '0002339',
      cdc: null,
    });
    expect(fetchMock.mock.calls[0][1].headers.authorization).toBe('Bearer tok');
  });

  it('ECAN/EINO: va por CDC, con iTiDE y sin rango', async () => {
    await service.consultarEventoEnMiddleware('http://mw', 'tok', ECAN, 5);
    expect(payloadEnviado()).toMatchObject({ iTiDE: 5, cdc: ECAN.cdc, dEst: null, dPunExp: null, dNumIn: null, dNumFin: null });
  });

  it('EINU: encuentra el registro bajo la clave "dEst-dPunExp-dNumIn/dNumFin"', async () => {
    fetchMock.mockResolvedValue({
      status: 200,
      json: async () => ({ status: 'success', response: { '001-001-0002339/0002339': REGISTRO, '001-001-0000001/0000001': { ...REGISTRO, estado_evento: 'otro' } } }),
    });
    const r = await service.consultarEventoEnMiddleware('http://mw', 'tok', EINU, 1);
    expect(r).toEqual({ ok: true, registro: REGISTRO });
  });

  it('ECAN: encuentra el registro bajo el CDC', async () => {
    fetchMock.mockResolvedValue({ status: 200, json: async () => ({ status: 'success', response: { [ECAN.cdc]: REGISTRO, otro: {} } }) });
    const r = await service.consultarEventoEnMiddleware('http://mw', 'tok', ECAN, 1);
    expect(r).toEqual({ ok: true, registro: REGISTRO });
  });

  it('respuesta sin el evento = registro null (habilita liberar)', async () => {
    const r = await service.consultarEventoEnMiddleware('http://mw', 'tok', EINU, 1);
    expect(r).toEqual({ ok: true, registro: null });
  });
});

describe('MiddlewareSifenService.consultarEstadoEvento (chequeo tras enviar)', () => {
  const crear = () => {
    const service = Object.create(MiddlewareSifenService.prototype) as any;
    service.login = jest.fn().mockResolvedValue({ token: 'tok' });
    return service;
  };
  const respuesta = (retorno: Record<string, unknown> | null) => ({
    status: 200,
    json: async () => ({
      status: 'success',
      response: { '001-001-0002339/0002339': { estado_evento: 'Documento Firmado', retorno_sifen: retorno } },
    }),
  });
  const DOC = { cdc: null, dest: '001', dpunexp: '001', dnumdoc: '0002339' };

  it('lee el estado de retorno_sifen del registro (formato real), no de la raíz', async () => {
    process.env.MIDDLEWARE_SIFEN_URL = process.env.MIDDLEWARE_SIFEN_URL || 'http://mw';
    const service = crear();
    global.fetch = jest.fn().mockResolvedValue(respuesta({ estado: 'Aprobado', mensaje: 'Evento aprobado', codrespuesta: '0600' })) as any;
    const r = await service.consultarEstadoEvento('emp', DOC, 'EINU', 1);
    expect(r).toEqual({ estado: 'Aprobado', mensaje: 'Evento aprobado' });
  });

  it('sin retorno de SIFEN todavía = Pendiente', async () => {
    const service = crear();
    global.fetch = jest.fn().mockResolvedValue(respuesta({ estado: null, mensaje: null })) as any;
    const r = await service.consultarEstadoEvento('emp', DOC, 'EINU', 1);
    expect(r.estado).toBe('Pendiente');
  });
});
