jest.mock('src/config', () => ({ envs: { bancardEncryptionKey: '0123456789abcdef0123456789abcdef' } }));

import { BancardConfigService } from './bancard-config.service';

/**
 * Carril B › T1. `GET/PUT /bancard/config` devolvían el `webhook_secret` en claro (hallazgo de C0) y el PUT borraba lo
 * que no viajaba: sin `webhook_secret` lo dejaba en null y las cuatro `cuenta_contable_*` también (`?? null`). Ahora:
 * ninguna respuesta lleva `webhook_secret` ni la clave privada (tampoco cifrada), en su lugar `tiene_webhook_secret` /
 * `tiene_private_key`; un secreto omitido o vacío conserva el guardado y un campo omitido no se toca.
 */
const guardada = {
  id: 'b1',
  empresa_id: 'e1',
  ambiente: 'staging',
  public_key: 'pub',
  private_key_encrypted: 'aa:bb',
  return_url_base: 'https://x/ok',
  cancel_url_base: 'https://x/no',
  webhook_secret: 'secreto-viejo',
  cuenta_contable_por_liquidar: 'c1',
  cuenta_contable_banco: 'c2',
  cuenta_contable_comision: 'c3',
  cuenta_contable_iva_comision: 'c4',
  porcentaje_comision_credito: 3.5,
  porcentaje_comision_debito: 2.5,
  timeout_segundos: 1800,
  activo: true,
  created_at: new Date(),
  updated_at: new Date(),
};

function crear(existente: Record<string, unknown> | null = guardada) {
  let fila: any = existente ? { ...existente } : null;
  const prisma: any = {
    bancard_config: {
      findUnique: jest.fn(async () => fila),
      upsert: jest.fn(async ({ create, update }: any) => {
        const datos = Object.fromEntries(Object.entries(fila ? update : create).filter(([, v]) => v !== undefined));
        fila = { ...(fila ?? {}), ...datos };
        return fila;
      }),
    },
  };
  return { service: new BancardConfigService(prisma), prisma, fila: () => fila };
}

const sinSecretos = (r: any) => {
  expect(r).not.toHaveProperty('webhook_secret');
  expect(r).not.toHaveProperty('private_key');
  expect(r).not.toHaveProperty('private_key_encrypted');
  expect(JSON.stringify(r)).not.toContain('secreto');
  expect(JSON.stringify(r)).not.toContain('aa:bb');
};

describe('bancard-config: secretos', () => {
  it('GET no devuelve el webhook_secret ni la clave privada; dice si hay uno guardado', async () => {
    const r = await crear().service.getConfig('e1');
    sinSecretos(r);
    expect(r).toMatchObject({ tiene_webhook_secret: true, tiene_private_key: true, public_key: 'pub' });
  });

  it('GET sin secretos guardados → tiene_* false', async () => {
    const r = await crear({ ...guardada, webhook_secret: null, private_key_encrypted: null }).service.getConfig('e1');
    expect(r).toMatchObject({ tiene_webhook_secret: false, tiene_private_key: false });
  });

  it('PUT no devuelve secretos (tampoco el nuevo)', async () => {
    const r = await crear().service.upsertConfig('e1', { webhook_secret: 'secreto-nuevo', private_key: 'secreto-clave' });
    sinSecretos(r);
    expect(r).toMatchObject({ tiene_webhook_secret: true, tiene_private_key: true });
  });

  it.each([
    ['omitido', {}],
    ['vacío', { webhook_secret: '', private_key: '' }],
  ])('PUT con el secreto %s conserva el guardado', async (_n, dto) => {
    const { service, fila } = crear();
    await service.upsertConfig('e1', { public_key: 'pub2', ...dto });
    expect(fila()).toMatchObject({ webhook_secret: 'secreto-viejo', private_key_encrypted: 'aa:bb', public_key: 'pub2' });
  });

  it('PUT sin las cuentas contables conserva las cuatro', async () => {
    const { service, fila } = crear();
    await service.upsertConfig('e1', { activo: false });
    expect(fila()).toMatchObject({
      cuenta_contable_por_liquidar: 'c1',
      cuenta_contable_banco: 'c2',
      cuenta_contable_comision: 'c3',
      cuenta_contable_iva_comision: 'c4',
      activo: false,
    });
  });

  it('PUT con un webhook_secret nuevo lo reemplaza', async () => {
    const { service, fila } = crear();
    await service.upsertConfig('e1', { webhook_secret: 'secreto-nuevo' });
    expect(fila().webhook_secret).toBe('secreto-nuevo');
  });

  it('alta sin secretos → tiene_* false', async () => {
    const r = await crear(null).service.upsertConfig('e1', { public_key: 'pub' });
    expect(r).toMatchObject({ tiene_webhook_secret: false, tiene_private_key: false });
    sinSecretos(r);
  });
});
