import { Prisma } from '@prisma/client';
import { REQUIRE_ALGUN_PRIVILEGIO_KEY, tieneAlgunPrivilegio } from '../auth/guards/algun-privilegio.guard';
import { REQUIRE_PERMISSION_KEY } from '../auth/decorators/require-permission.decorator';
import { REQUIRE_SUBMODULO_KEY } from '../auth/decorators/require-submodulo.decorator';
import { PermissionGuard } from '../auth/guards/permission.guard';
import { SubmoduloGuard, submoduloHabilitado } from '../auth/guards/submodulo.guard';
import { TesoreriaController } from './tesoreria.controller';
import { TesoreriaService } from './tesoreria.service';

jest.mock('../auth/guards/submodulo.guard', () => ({ ...jest.requireActual('../auth/guards/submodulo.guard'), submoduloHabilitado: jest.fn() }));
jest.mock('../auth/guards/algun-privilegio.guard', () => ({ ...jest.requireActual('../auth/guards/algun-privilegio.guard'), tieneAlgunPrivilegio: jest.fn() }));
// El alcance de sucursal de la sesión (T2 carril C) tiene su propio spec: acá, usuario sin restricción.
jest.mock('../utils/alcance-sucursal', () => ({ ...jest.requireActual('../utils/alcance-sucursal'), alcanceSucursalUsuario: jest.fn().mockResolvedValue(null) }));

const EMP = '0e000000-0000-4000-8000-000000000001';
const SESION = '5e510000-0000-4000-8000-000000000001';
const ARQUEO = 'a4c00000-0000-4000-8000-000000000001';
const FACT_USD = 'fac00000-0000-4000-8000-000000000001';
const USER = { id: 'u-1', empresa_id: EMP } as never;

const LINEA_MEZCLA = 'Sesión con documentos en PYG y USD: el resumen y el arqueo muestran los acumulados de la caja, sin convertir.';

const sesionFila = (over = {}) => ({
  id: SESION,
  estado: 'ABIERTA',
  monto_apertura: 0,
  monto_ventas_efectivo: 0,
  monto_ventas_otros: 0,
  monto_entradas_manual: 0,
  monto_salidas_manual: 0,
  monto_final_sistema: null,
  monto_cierre: null,
  observaciones: null,
  fecha_apertura: new Date('2026-10-01T12:00:00Z'),
  fecha_cierre: null,
  sucursal_id: null,
  cajas: { id: 'c1', descripcion: 'Caja 1', sucursal_id: null },
  empresas_sucursales: null,
  usuario: { nombres: 'Ana' },
  movimiento_cajas: [],
  arqueo_cajas: [],
  ...over,
});

const movimiento = (over = {}) => ({
  id: 'm1',
  referencia: null,
  monto: 0,
  descripcion: 'Apertura',
  fecha_mov: new Date('2026-10-01T12:00:00Z'),
  tipo_movimiento_cajas: { descripcion: 'Entrada' },
  usuario: { nombres: 'Ana' },
  ...over,
});

interface Opciones {
  sesion?: unknown;
  ventas?: unknown[];
  cobros?: unknown[];
  monedas?: string[];
  facturas?: unknown[];
  recibos?: unknown[];
  arqueo?: unknown;
  respuesta?: unknown;
}

function armar(o: Opciones = {}) {
  const sqls: string[] = [];
  const service = Object.create(TesoreriaService.prototype) as any;
  service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
  service.buildCobrosDetalleArqueo = jest.fn().mockResolvedValue([{ recibo_id: 'r', moneda: 'PYG' }]);
  service.prisma = {
    sesiones_caja: {
      findFirst: jest.fn(async ({ where }: any) => {
        if (where.OR) return (service.__propia as unknown) ?? null;
        return 'sesion' in o ? o.sesion : sesionFila();
      }),
    },
    arqueo_cajas: { findFirst: jest.fn().mockResolvedValue('arqueo' in o ? o.arqueo : { sesion_id: SESION }) },
    empresas: { findFirst: jest.fn().mockResolvedValue({ razon_social: 'DOBA', ruc: '80144315', dv: '1' }) },
    empresas_sucursales: { findFirst: jest.fn().mockResolvedValue(null) },
    factura_cab: { findMany: jest.fn().mockResolvedValue(o.facturas ?? []) },
    recibos_cobro: { findMany: jest.fn().mockResolvedValue(o.recibos ?? []) },
    $queryRaw: jest.fn(async (strings: TemplateStringsArray, ...valores: unknown[]) => {
      const sql = Prisma.sql(strings, ...(valores as never[])).text;
      sqls.push(sql);
      if (sql.includes('DISTINCT')) return (o.monedas ?? []).map((moneda) => ({ moneda }));
      if (sql.includes('recibo_cobro_detalle')) return o.cobros ?? [];
      return o.ventas ?? [];
    }),
  };
  const fetchMock = jest.fn().mockResolvedValue(o.respuesta ?? { ok: true, arrayBuffer: async () => new TextEncoder().encode('%PDF-1.4').buffer });
  (global as any).fetch = fetchMock;
  const cuerpo = () => JSON.parse(fetchMock.mock.calls[0][1].body);
  return { service, fetchMock, cuerpo, sqls };
}

const errorDe = async (p: Promise<unknown>) => {
  try {
    await p;
    return undefined;
  } catch (e: any) {
    return { status: e.getStatus?.() ?? 500, ...(e.getResponse?.() ?? {}) } as Record<string, any>;
  }
};

const submodulo = submoduloHabilitado as jest.Mock;
const privilegio = tieneAlgunPrivilegio as jest.Mock;
const fetchOriginal = global.fetch;

beforeEach(() => {
  submodulo.mockResolvedValue({ habilitado: true, fechaFinPrueba: null });
  privilegio.mockResolvedValue(true);
});
afterAll(() => {
  global.fetch = fetchOriginal;
});

describe('payload del arqueo', () => {
  const ventaPyg = { medio_pago: 'Efectivo', moneda: 'PYG', cantidad: 2, total: 558500 };
  const ventaUsd = { medio_pago: 'Transferencia', moneda: 'USD', cantidad: 1, total: 110 };
  const movUsd = movimiento({ id: 'm2', referencia: FACT_USD, monto: 110, descripcion: 'Venta Fact. 001-001-0002521 - Transferencia' });
  const facturaUsd = { id: FACT_USD, moneda: { codigo: 'USD' }, factura_forma_pagos: [{ medio_pago_id: 'mp', dmontipag: 110, medio_pago: { descripcion: 'Transferencia' } }] };

  it('sesión solo PYG: moneda PYG, filas sin rótulos, sin línea de mezcla ni campos nuevos', async () => {
    const { service, cuerpo } = armar({ sesion: sesionFila({ monto_apertura: 100000, movimiento_cajas: [movimiento({ monto: 100000 })] }), monedas: ['PYG'], ventas: [ventaPyg] });
    await service.generarPdfArqueoSesion(SESION, EMP);
    const b = cuerpo();
    expect(b.moneda).toEqual({ codigo: 'PYG' });
    expect(b.ventas_por_medio).toEqual([{ medio_pago: 'Efectivo', cantidad: 2, total: 558500 }]);
    expect(b.arqueo.observaciones).toBeNull();
    expect(b).not.toHaveProperty('monedas_sesion');
    expect(b.movimientos[0]).toMatchObject({ concepto: 'Apertura', monto: 100000 });
    expect(b.movimientos[0]).not.toHaveProperty('moneda');
  });

  it('factura USD y PYG (f14a820f): PYG con filas rotuladas, TOTAL USD y la línea de la mezcla', async () => {
    const { service, cuerpo } = armar({
      sesion: sesionFila({ movimiento_cajas: [movUsd], observaciones: 'Observación previa' }),
      monedas: ['PYG', 'USD'],
      ventas: [ventaPyg, ventaUsd],
      facturas: [facturaUsd],
    });
    await service.generarPdfArqueoSesion(SESION, EMP);
    const b = cuerpo();
    expect(b.moneda).toEqual({ codigo: 'PYG' });
    expect(b.ventas_por_medio).toEqual([
      { medio_pago: 'Efectivo', cantidad: 2, total: 558500 },
      { medio_pago: 'Transferencia · US$ 110,00', cantidad: 1, total: 0 },
      { medio_pago: 'TOTAL USD · US$ 110,00', cantidad: null, total: 0 },
    ]);
    expect(b.movimientos[0].concepto).toBe('US$ 110,00 · Venta Fact. 001-001-0002521 - Transferencia');
    expect(b.movimientos[0].monto).toBe(0);
    expect(b.movimientos[0].tipo).toBe('ENTRADA');
    expect(b.arqueo.observaciones.startsWith(LINEA_MEZCLA)).toBe(true);
    expect(b.arqueo.observaciones).toContain('Observación previa');
    expect(b).not.toHaveProperty('monedas_sesion');
    expect(b.ventas_por_medio.every((f: object) => !('moneda' in f))).toBe(true);
    expect(b.movimientos.every((f: object) => !('moneda' in f))).toBe(true);
  });

  it('el mismo medio en dos monedas son dos filas, no una suma', async () => {
    const { service, cuerpo } = armar({
      monedas: ['PYG', 'USD'],
      ventas: [
        { medio_pago: 'Transferencia', moneda: 'PYG', cantidad: 3, total: 11990000 },
        { medio_pago: 'Transferencia', moneda: 'USD', cantidad: 7, total: 620 },
      ],
    });
    await service.generarPdfArqueoSesion(SESION, EMP);
    expect(cuerpo().ventas_por_medio).toEqual([
      { medio_pago: 'Transferencia', cantidad: 3, total: 11990000 },
      { medio_pago: 'Transferencia · US$ 620,00', cantidad: 7, total: 0 },
      { medio_pago: 'TOTAL USD · US$ 620,00', cantidad: null, total: 0 },
    ]);
  });

  it('ventas y cobros del mismo medio y moneda se suman', async () => {
    const { service, cuerpo } = armar({
      monedas: ['PYG'],
      ventas: [{ medio_pago: 'Efectivo', moneda: 'PYG', cantidad: 1, total: 100 }],
      cobros: [{ medio_pago: 'Efectivo', moneda: 'PYG', cantidad: 2, total: 50 }],
    });
    await service.generarPdfArqueoSesion(SESION, EMP);
    expect(cuerpo().ventas_por_medio).toEqual([{ medio_pago: 'Efectivo', cantidad: 3, total: 150 }]);
  });

  it('factura solo USD y apertura 0: moneda USD, filas sin rótulo', async () => {
    const { service, cuerpo } = armar({ sesion: sesionFila({ movimiento_cajas: [movUsd] }), monedas: ['USD'], ventas: [ventaUsd], facturas: [facturaUsd] });
    await service.generarPdfArqueoSesion(SESION, EMP);
    const b = cuerpo();
    expect(b.moneda).toEqual({ codigo: 'USD' });
    expect(b.ventas_por_medio).toEqual([{ medio_pago: 'Transferencia', cantidad: 1, total: 110 }]);
    expect(b.movimientos[0]).toMatchObject({ monto: 110, concepto: 'Venta Fact. 001-001-0002521 - Transferencia' });
  });

  it('la apertura de la caja en guaraníes con una factura USD crea la mezcla', async () => {
    const { service, cuerpo } = armar({ sesion: sesionFila({ monto_apertura: 100000 }), monedas: ['USD'], ventas: [ventaUsd] });
    await service.generarPdfArqueoSesion(SESION, EMP);
    expect(cuerpo().moneda).toEqual({ codigo: 'PYG' });
    expect(cuerpo().arqueo.observaciones.startsWith(LINEA_MEZCLA)).toBe(true);
  });

  it('un recibo en USD también lleva el monto en el texto', async () => {
    const { service, cuerpo } = armar({
      sesion: sesionFila({ movimiento_cajas: [movimiento({ referencia: 'b0000000-0000-4000-8000-000000000001', monto: 50, descripcion: 'Cobro cuota' })] }),
      monedas: ['PYG', 'USD'],
      ventas: [ventaPyg],
      cobros: [{ medio_pago: 'Efectivo', moneda: 'USD', cantidad: 1, total: 50 }],
      recibos: [{ id: 'b0000000-0000-4000-8000-000000000001', moneda: { codigo: 'USD' }, recibo_cobro_detalle: [] }],
    });
    await service.generarPdfArqueoSesion(SESION, EMP);
    const b = cuerpo();
    expect(b.ventas_por_medio).toContainEqual({ medio_pago: 'Efectivo · US$ 50,00', cantidad: 1, total: 0 });
    expect(b.movimientos[0].concepto).toBe('US$ 50,00 · Cobro cuota');
  });

  it('un documento sin moneda cuenta como PYG', async () => {
    const { service, cuerpo } = armar({
      sesion: sesionFila({ movimiento_cajas: [movimiento({ referencia: FACT_USD, monto: 7 })] }),
      monedas: ['PYG', 'USD'],
      facturas: [{ id: FACT_USD, moneda: null, factura_forma_pagos: [] }],
    });
    await service.generarPdfArqueoSesion(SESION, EMP);
    expect(cuerpo().movimientos[0].monto).toBe(7);
  });

  describe('F5: lo diferido y lo anulado no cuentan', () => {
    const FILTRO = ['COALESCE(fc.cobro_diferido, false) = false', "COALESCE(fc.estado, '') NOT IN ('Anulado', 'Cancelado', 'Inutilizado')"];

    it('los dos $queryRaw de facturas llevan el mismo filtro', async () => {
      const { service, sqls } = armar();
      await service.generarPdfArqueoSesion(SESION, EMP);
      // La de ventas por condición (informativa) es aparte: incluye el cobro en ruta a propósito.
      const deFacturas = sqls.filter((s) => s.includes('factura_cab') && !s.includes('sesion_caja_id = ANY'));
      expect(deFacturas).toHaveLength(2);
      for (const sql of deFacturas) for (const parte of FILTRO) expect(sql).toContain(parte);
    });

    it('las monedas y los cobros no cuentan los recibos anulados', async () => {
      const { service, sqls } = armar();
      await service.generarPdfArqueoSesion(SESION, EMP);
      const deRecibos = sqls.filter((s) => s.includes('recibos_cobro'));
      expect(deRecibos).toHaveLength(2);
      for (const sql of deRecibos) expect(sql).toContain("rc.estado <> 'anulado'");
    });

    it('todas las consultas suman la moneda con COALESCE a PYG', async () => {
      const { service, sqls } = armar();
      await service.generarPdfArqueoSesion(SESION, EMP);
      // Monedas, ventas por medio, cobros por medio y ventas por condición (la fecha de la migración no suma montos).
      const deMontos = sqls.filter((s) => !s.includes('_prisma_migrations'));
      expect(deMontos).toHaveLength(4);
      for (const sql of deMontos) expect(sql).toContain("COALESCE(m.codigo, 'PYG')");
    });

    it('sin una moneda de la consulta (la factura USD anulada quedó afuera) no hay mezcla ni línea', async () => {
      // La consulta ya la filtró: el movimiento de esa factura todavía existe y no crea mezcla.
      const { service, cuerpo } = armar({
        sesion: sesionFila({ movimiento_cajas: [movimiento({ referencia: FACT_USD, monto: 110 })] }),
        monedas: ['PYG'],
        ventas: [ventaPyg],
        facturas: [facturaUsd],
      });
      await service.generarPdfArqueoSesion(SESION, EMP);
      expect(cuerpo().moneda).toEqual({ codigo: 'PYG' });
      expect(cuerpo().arqueo.observaciones).toBeNull();
      // La fila de esa factura no sale como guaraníes: lleva su monto en el texto y no suma.
      expect(cuerpo().movimientos[0]).toMatchObject({ concepto: 'US$ 110,00 · Apertura', monto: 0 });
      expect(cuerpo().ventas_por_medio).toEqual([{ medio_pago: 'Efectivo', cantidad: 2, total: 558500 }]);
    });

    it('al revés: en una sesión solo USD, la factura PYG anulada no sale como dólares', async () => {
      const facturaPyg = { ...facturaUsd, moneda: { codigo: 'PYG' } };
      const { service, cuerpo } = armar({
        sesion: sesionFila({ movimiento_cajas: [movimiento({ referencia: FACT_USD, monto: 150000, descripcion: 'Venta anulada' })] }),
        monedas: ['USD'],
        ventas: [ventaUsd],
        facturas: [facturaPyg],
      });
      await service.generarPdfArqueoSesion(SESION, EMP);
      expect(cuerpo().moneda).toEqual({ codigo: 'USD' });
      expect(cuerpo().arqueo.observaciones).toBeNull();
      expect(cuerpo().movimientos[0]).toMatchObject({ concepto: 'Gs. 150.000 · Venta anulada', monto: 0 });
    });
  });

  it('a4 no lleva cobros_detalle; a4-detallado y ticket-detallado, sí, con moneda', async () => {
    for (const [formato, lleva] of [
      ['a4', false],
      ['ticket', false],
      ['a4-detallado', true],
      ['ticket-detallado', true],
    ] as const) {
      const { service, cuerpo } = armar({ monedas: ['PYG'] });
      await service.generarPdfArqueoSesion(SESION, EMP, formato);
      const b = cuerpo();
      expect(b.formato).toBe(formato);
      if (lleva) expect(b.cobros_detalle[0].moneda).toBe('PYG');
      else expect(b).not.toHaveProperty('cobros_detalle');
    }
  });
});

describe('errores del arqueo', () => {
  it('sesión ajena → 404 SESION_NO_ENCONTRADA', async () => {
    const { service, fetchMock } = armar({ sesion: null });
    expect(await errorDe(service.generarPdfArqueoSesion(SESION, EMP))).toMatchObject({ status: 404, codigo: 'SESION_NO_ENCONTRADA' });
    expect(fetchMock).not.toHaveBeenCalled();
  });

  it('arqueo_id de otra sesión → 404 ARQUEO_NO_ENCONTRADO (hoy caía a los datos de la sesión)', async () => {
    const { service, fetchMock } = armar({ sesion: sesionFila({ arqueo_cajas: [{ id: ARQUEO, fecha: new Date(), total_contado: 1 }] }) });
    expect(await errorDe(service.generarPdfArqueoSesion(SESION, EMP, 'a4', 'b4c00000-0000-4000-8000-000000000009'))).toMatchObject({ status: 404, codigo: 'ARQUEO_NO_ENCONTRADO' });
    expect(fetchMock).not.toHaveBeenCalled();
  });

  it('arqueo_id de la sesión pasa', async () => {
    const { service, fetchMock } = armar({ sesion: sesionFila({ arqueo_cajas: [{ id: ARQUEO, fecha: new Date(), total_contado: 1 }] }) });
    await service.generarPdfArqueoSesion(SESION, EMP, 'a4', ARQUEO);
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  it('arqueo no UUID → 404 ARQUEO_NO_ENCONTRADO, sin consultar', async () => {
    const { service } = armar();
    expect(await errorDe(service.generarPdfArqueo('no-uuid', EMP))).toMatchObject({ status: 404, codigo: 'ARQUEO_NO_ENCONTRADO' });
    expect(service.prisma.arqueo_cajas.findFirst).not.toHaveBeenCalled();
  });

  it('arqueo ajeno → 404 ARQUEO_NO_ENCONTRADO', async () => {
    const { service } = armar({ arqueo: null });
    expect(await errorDe(service.generarPdfArqueo(ARQUEO, EMP))).toMatchObject({ status: 404, codigo: 'ARQUEO_NO_ENCONTRADO' });
  });

  it('el generador responde 500 con detalle → 502 GENERADOR_PDF_ERROR sin el cuerpo crudo; se loguea', async () => {
    const { service } = armar({ respuesta: { ok: false, status: 500, text: async () => 'detalle secreto' } });
    const e = await errorDe(service.generarPdfArqueoSesion(SESION, EMP));
    expect(e).toMatchObject({ status: 502, codigo: 'GENERADOR_PDF_ERROR' });
    expect(e?.message).not.toContain('detalle secreto');
    expect(service.logger.error.mock.calls[0][0]).toContain('detalle secreto');
  });

  it('fetch rechaza → 502 igual', async () => {
    const { service, fetchMock } = armar();
    fetchMock.mockRejectedValue(new TypeError('fetch failed'));
    const e = await errorDe(service.generarPdfArqueoSesion(SESION, EMP));
    expect(e).toMatchObject({ status: 502, codigo: 'GENERADOR_PDF_ERROR' });
    expect(e?.message).not.toContain('fetch failed');
  });

  it('F13: fetch recibe un signal y un TimeoutError da 502', async () => {
    const espia = jest.spyOn(AbortSignal, 'timeout');
    const { service, fetchMock } = armar();
    const timeout = new Error('The operation was aborted due to timeout');
    timeout.name = 'TimeoutError';
    fetchMock.mockRejectedValue(timeout);
    expect(await errorDe(service.generarPdfArqueoSesion(SESION, EMP))).toMatchObject({ status: 502, codigo: 'GENERADOR_PDF_ERROR' });
    expect(espia).toHaveBeenCalledWith(120_000);
    expect(fetchMock.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
    espia.mockRestore();
  });
});

describe('exigirPuedeVerPdfSesion', () => {
  it('sin ARQUEAR, en una ajena → 403 ARQUEO_SIN_PERMISO con el texto de hoy', async () => {
    privilegio.mockResolvedValue(false);
    const { service } = armar();
    expect(await errorDe(service.exigirPuedeVerPdfSesion(SESION, EMP, 'u-1'))).toMatchObject({
      status: 403,
      codigo: 'ARQUEO_SIN_PERMISO',
      message: 'Para ver el arqueo de una caja que no abriste ni cerraste hace falta el permiso «Arquear caja» (Tesorería › Cajas).',
    });
  });

  it('sin ARQUEAR, en la propia, pasa', async () => {
    privilegio.mockResolvedValue(false);
    const { service } = armar();
    service.__propia = { id: SESION };
    await expect(service.exigirPuedeVerPdfSesion(SESION, EMP, 'u-1')).resolves.toBeUndefined();
  });

  it('con ARQUEAR pasa sin mirar de quién es', async () => {
    const { service } = armar();
    await expect(service.exigirPuedeVerPdfSesion(SESION, EMP, 'u-1')).resolves.toBeUndefined();
  });

  describe('D14: TES_CAJAS o VENTAS_POS', () => {
    const excluidos = (...codigos: string[]) =>
      submodulo.mockImplementation(async (_p, _e, c) =>
        codigos.includes(c) ? { habilitado: false, causa: 'excluido', mensaje: `sin ${c}` } : { habilitado: true, fechaFinPrueba: null },
      );

    it('sin ninguno → 403', async () => {
      excluidos('TES_CAJAS', 'VENTAS_POS');
      const { service } = armar();
      expect(await errorDe(service.exigirPuedeVerPdfSesion(SESION, EMP, 'u-1'))).toMatchObject({ status: 403 });
    });
    it('sin TES_CAJAS y con VENTAS_POS, pasa', async () => {
      excluidos('TES_CAJAS');
      await expect(armar().service.exigirPuedeVerPdfSesion(SESION, EMP, 'u-1')).resolves.toBeUndefined();
    });
    it('con TES_CAJAS y sin VENTAS_POS, pasa', async () => {
      excluidos('VENTAS_POS');
      await expect(armar().service.exigirPuedeVerPdfSesion(SESION, EMP, 'u-1')).resolves.toBeUndefined();
    });
    afterEach(() => submodulo.mockReset());
  });
});

describe('handlers', () => {
  const res = () => ({ writeHead: jest.fn(), end: jest.fn() }) as any;

  describe('getArqueoSesionPdf (F7: validar antes de exigir)', () => {
    const controlador = () => {
      const { service, fetchMock } = armar();
      const exigir = jest.spyOn(service, 'exigirPuedeVerPdfSesion').mockRejectedValue(new Error('no debía llamarse'));
      return { controller: new TesoreriaController(service), service, fetchMock, exigir };
    };

    it('sin ARQUEAR, formato pdf → 400 FORMATO_INVALIDO, sin exigir ni fetch', async () => {
      const { controller, exigir, fetchMock } = controlador();
      expect(await errorDe(controller.getArqueoSesionPdf(SESION, 'pdf' as never, undefined, USER, res()))).toMatchObject({
        status: 400,
        codigo: 'FORMATO_INVALIDO',
        campo: 'formato',
      });
      expect(exigir).not.toHaveBeenCalled();
      expect(fetchMock).not.toHaveBeenCalled();
    });

    it('sin ARQUEAR, sesion no UUID → 404 SESION_NO_ENCONTRADA, sin error de Prisma', async () => {
      const { controller, exigir, service } = controlador();
      expect(await errorDe(controller.getArqueoSesionPdf('no-uuid', 'a4', undefined, USER, res()))).toMatchObject({ status: 404, codigo: 'SESION_NO_ENCONTRADA' });
      expect(exigir).not.toHaveBeenCalled();
      expect(service.prisma.sesiones_caja.findFirst).not.toHaveBeenCalled();
    });

    it('con formato y UUID válidos recién ahí exige', async () => {
      const { controller, exigir, service } = controlador();
      exigir.mockResolvedValue(undefined as never);
      const r = res();
      await controller.getArqueoSesionPdf(SESION, undefined as never, undefined, USER, r);
      expect(exigir).toHaveBeenCalledWith(SESION, EMP, 'u-1');
      expect(r.writeHead).toHaveBeenCalledWith(200, expect.objectContaining({ 'Content-Type': 'application/pdf' }));
      expect(service.prisma.sesiones_caja.findFirst).toHaveBeenCalled();
    });

    it('la propiedad falla antes de generar', async () => {
      const { controller, exigir, fetchMock } = controlador();
      exigir.mockRejectedValue(Object.assign(new Error('x'), { getStatus: () => 403, getResponse: () => ({ codigo: 'ARQUEO_SIN_PERMISO' }) }));
      expect(await errorDe(controller.getArqueoSesionPdf(SESION, 'a4', undefined, USER, res()))).toMatchObject({ status: 403, codigo: 'ARQUEO_SIN_PERMISO' });
      expect(fetchMock).not.toHaveBeenCalled();
    });
  });

  describe('getArqueoPdf', () => {
    it('formato pdf → 400 FORMATO_INVALIDO, sin fetch', async () => {
      const { service, fetchMock } = armar();
      expect(await errorDe(new TesoreriaController(service).getArqueoPdf(ARQUEO, 'pdf' as never, USER, res()))).toMatchObject({ status: 400, codigo: 'FORMATO_INVALIDO' });
      expect(fetchMock).not.toHaveBeenCalled();
    });
    it('sin formato → a4', async () => {
      const { service, cuerpo } = armar({ sesion: sesionFila({ arqueo_cajas: [{ id: ARQUEO, fecha: new Date(), total_contado: 1 }] }) });
      await new TesoreriaController(service).getArqueoPdf(ARQUEO, undefined as never, USER, res());
      expect(cuerpo().formato).toBe('a4');
    });
  });

  describe('metadata', () => {
    const proto = TesoreriaController.prototype as any;

    it('getArqueoPdf con TES_CAJAS y TES_CAJ_CAJA_ARQUEAR', () => {
      expect(Reflect.getMetadata(REQUIRE_SUBMODULO_KEY, proto.getArqueoPdf)).toBe('TES_CAJAS');
      expect(Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto.getArqueoPdf)).toEqual({ modulo: 'TESORERIA', privilegio: 'TES_CAJ_CAJA_ARQUEAR' });
      expect(Reflect.getMetadata('__guards__', proto.getArqueoPdf)).toEqual([SubmoduloGuard, PermissionGuard]);
    });

    it('getArqueoSesionPdf sin guard de submódulo y con sus tres privilegios', () => {
      expect(Reflect.getMetadata(REQUIRE_SUBMODULO_KEY, proto.getArqueoSesionPdf)).toBeUndefined();
      expect(Reflect.getMetadata('__guards__', proto.getArqueoSesionPdf)).not.toContain(SubmoduloGuard);
      expect(Reflect.getMetadata(REQUIRE_ALGUN_PRIVILEGIO_KEY, proto.getArqueoSesionPdf)).toEqual(['TES_CAJ_CAJA_ARQUEAR', 'TES_CAJ_CAJA_CERRAR', 'VEN_POS_CIERRE_CAJA']);
    });
  });
});
