import { CajasService } from 'src/cajas/cajas.service';
import { InteresesMoratoriosService } from 'src/cobranzas/intereses-moratorios.service';
import { PuntoExpedicionesService } from 'src/punto-expediciones/punto-expediciones.service';
import { SucursalesService } from 'src/sucursales/sucursales.service';
import { SyncService } from 'src/sync/sync.service';
import { NumeracionesService } from './numeraciones.service';

jest.mock('src/utils/alcance-sucursal', () => ({
  ...jest.requireActual('src/utils/alcance-sucursal'),
  alcanceSucursalUsuario: jest.fn().mockResolvedValue(null),
}));
jest.mock('src/auth/guards/tiene-permiso', () => ({ tienePermiso: jest.fn().mockResolvedValue(false) }));

/**
 * Ninguna respuesta HTTP que traiga el timbrado de una numeración devuelve el CSC de SIFEN (ni el id del CSC ni quién lo
 * cargó): el timbrado viaja con sus datos públicos (número, inicio de vigencia, ambiente). La emisión SIFEN lee el CSC
 * por su cuenta (cola del middleware), nunca de estas respuestas.
 *
 * La base es un Prisma "falso" que respeta `include`/`select` como el de verdad: con `timbrado: true` devuelve la fila
 * completa (CSC incluido), con `select` solo los campos pedidos. Así el test mira lo que de verdad saldría al front.
 */
const NUM = '11111111-1111-4111-8111-111111111111';
const EMP = '22222222-2222-4222-8222-222222222222';
const SUC = '44444444-4444-4444-8444-444444444444';
const PUNTO = '66666666-6666-4666-8666-666666666666';
const TIMB = '77777777-7777-4777-8777-777777777777';
const CSC = 'CSC-SECRETO-ABC123';

const TIMBRADO_COMPLETO = {
  id: TIMB,
  empresa_id: EMP,
  num_timbrado: '17000001',
  fecha_inicio: new Date('2026-01-01'),
  id_csc: '0001',
  csc: CSC,
  ambiente: 'test',
  usuario: 'quien-lo-cargo',
  created_at: new Date('2026-01-01'),
  updated_at: new Date('2026-01-01'),
};
const CAMPOS_PUBLICOS = ['id', 'num_timbrado', 'fecha_inicio', 'ambiente'];

const LISTAS = new Set(['numeraciones_documento', 'puntos_expedicion', 'cajas', 'asignaciones_usuarios']);

const fila = (rel: string): Record<string, unknown> =>
  rel === 'timbrado' || rel === 'empresas_timbrado'
    ? { ...TIMBRADO_COMPLETO }
    : {
        id: rel === 'numeraciones_documento' ? NUM : `${rel}-1`,
        empresa_id: EMP,
        sucursal_id: SUC,
        punto_expedicion_id: PUNTO,
        timbrado_id: TIMB,
        numeracion_id: NUM,
        numero_actual: 1,
        numero_inicial: 1,
        numero_final: null,
        active: false,
        descripcion: rel,
      };

/** Lo que Prisma devolvería para la relación `rel` con ese `include`/`select`. */
function armar(rel: string, spec: unknown): unknown {
  if (!spec) return undefined;
  const base = fila(rel);
  const uno = () => {
    if (spec === true) return base;
    const s = spec as { select?: Record<string, unknown>; include?: Record<string, unknown> };
    const salida: Record<string, unknown> = s.select ? {} : { ...base };
    for (const [k, v] of Object.entries(s.select ?? s.include ?? {})) {
      if (!v) continue;
      if (v === true && k in base) salida[k] = base[k];
      else salida[k] = armar(k, v);
    }
    return salida;
  };
  return LISTAS.has(rel) ? [uno()] : uno();
}

const crearPrisma = () => {
  const modelo = (nombre: string) => {
    const rel = nombre === 'numeraciones_documento' ? 'raiz' : nombre;
    const una = (args: any = {}) => Promise.resolve(armar(rel, args.select || args.include ? args : true));
    return {
      findFirst: jest.fn(una),
      findUnique: jest.fn(una),
      update: jest.fn(una),
      create: jest.fn(una),
      findMany: jest.fn((args: any = {}) => Promise.resolve([armar(rel, args.select || args.include ? args : true)])),
      updateMany: jest.fn().mockResolvedValue({ count: 1 }),
      count: jest.fn().mockResolvedValue(0),
    };
  };
  const modelos: Record<string, ReturnType<typeof modelo>> = {};
  const prisma: any = new Proxy(
    {},
    {
      get: (_t, prop: string) => {
        if (prop === '$transaction') return (arg: any) => (typeof arg === 'function' ? arg(prisma) : Promise.all(arg));
        if (prop === '$queryRaw')
          return () => Promise.resolve([{ id: NUM, empresa_id: EMP, numero_actual: 1, numero_inicial: 1, numero_final: null, active: true, timbrado_id: TIMB }]);
        if (prop === 'then') return undefined;
        return (modelos[prop] ??= modelo(prop));
      },
    },
  );
  return prisma;
};

const audit = () => ({ log: jest.fn(), logEnTransaccion: jest.fn() }) as any;

/** Recorre la respuesta: ningún `csc`/`id_csc`/`usuario` del timbrado y cada timbrado solo con campos públicos. */
function timbradosDe(valor: unknown, encontrados: Record<string, unknown>[] = []): Record<string, unknown>[] {
  if (Array.isArray(valor)) valor.forEach((v) => timbradosDe(v, encontrados));
  else if (valor && typeof valor === 'object' && !(valor instanceof Date)) {
    for (const [k, v] of Object.entries(valor)) {
      if (k === 'timbrado' && v && typeof v === 'object') encontrados.push(v as Record<string, unknown>);
      timbradosDe(v, encontrados);
    }
  }
  return encontrados;
}

function sinSecretos(respuesta: unknown) {
  expect(JSON.stringify(respuesta)).not.toContain(CSC);
  const timbrados = timbradosDe(respuesta);
  expect(timbrados.length).toBeGreaterThan(0);
  for (const t of timbrados) {
    expect(t).not.toHaveProperty('csc');
    expect(t).not.toHaveProperty('id_csc');
    expect(t).not.toHaveProperty('usuario');
    expect(Object.keys(t).sort()).toEqual([...CAMPOS_PUBLICOS].sort());
    expect(t.num_timbrado).toBe('17000001');
  }
}

describe('Timbrado sin CSC en las respuestas', () => {
  const numeraciones = () => new NumeracionesService(crearPrisma(), audit());

  it('GET /numeraciones?punto_expedicion_id', async () => {
    sinSecretos(await numeraciones().findAllByPuntoExpedicion(PUNTO, EMP, 'u'));
  });

  it('GET /numeraciones/sucursal/:id y /numeraciones/lookup/sucursal/:id', async () => {
    sinSecretos(await numeraciones().findAllBySucursal(SUC, EMP, 'u'));
    sinSecretos(await numeraciones().findAllBySucursal(SUC, EMP, 'u', undefined, true));
  });

  it('GET /numeraciones/:id', async () => {
    sinSecretos(await numeraciones().findOne(NUM, EMP, 'u'));
  });

  it('POST /numeraciones (alta y reactivación)', async () => {
    sinSecretos(
      await numeraciones().create({ punto_expedicion_id: PUNTO, tipo_documento_id: 'td', timbrado_id: TIMB, numero_inicial: 1 } as any, EMP, 'u'),
    );
  });

  it('PUT /numeraciones/:id y PATCH /numeraciones/:id/correlativo', async () => {
    sinSecretos(await numeraciones().update(NUM, { active: true } as any, EMP, 'u'));
    sinSecretos(await numeraciones().ajustarCorrelativo(NUM, { numero_actual: 5, motivo: 'ajuste de prueba largo' } as any, EMP, 'u'));
  });

  it('GET /sucursales/:id/detalle ( con cajas, puntos y numeraciones)', async () => {
    const service = new SucursalesService({} as any, crearPrisma(), {} as any, audit());
    sinSecretos(await service.findOneWithRelations(SUC, EMP, 'u'));
  });

  it('GET /punto-expediciones/:id', async () => {
    const service = new PuntoExpedicionesService({} as any, {} as any, crearPrisma(), audit());
    sinSecretos(await service.findOne(PUNTO, EMP));
  });

  it('GET /cajas/:id', async () => {
    const service = new CajasService(crearPrisma(), audit());
    sinSecretos(await service.findOne('caja-1', EMP));
  });

  it('GET /cobranzas/intereses-moratorios/config (numeración guardada)', async () => {
    const service = new InteresesMoratoriosService(crearPrisma(), {} as any, {} as any, {} as any);
    sinSecretos(await service.getConfig(EMP));
  });

  it('GET /sync/numeraciones (POS offline: se guarda en el navegador)', async () => {
    const service = new SyncService(crearPrisma(), {} as any, audit(), {} as any);
    sinSecretos(await service.getNumeraciones(EMP));
  });
});
