import { createPrivateKey, generateKeyPairSync } from 'node:crypto';
import { buildBffSigningKey } from './bff-signing-key';
import { JwksPublisher } from './jwks.publisher';

async function makePublisher() {
  const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
  const key = await buildBffSigningKey({
    privateKey: createPrivateKey(privateKey.export({ type: 'pkcs8', format: 'pem' })),
    kid: 'bff-2026-05',
    alg: 'RS256',
  });
  return { publisher: new JwksPublisher(key), key };
}

describe('JwksPublisher', () => {
  it('returns a JWKS-shaped object with the single configured public key', async () => {
    const { publisher, key } = await makePublisher();
    const res = publisher.jwks();
    expect(Array.isArray(res.keys)).toBe(true);
    expect(res.keys).toHaveLength(1);
    expect(res.keys[0]).toBe(key.publicJwk);
  });

  it('the served key carries the kid + alg + use=sig the signing-key derived', async () => {
    const { publisher } = await makePublisher();
    const [jwk] = publisher.jwks().keys;
    expect(jwk?.kid).toBe('bff-2026-05');
    expect(jwk?.alg).toBe('RS256');
    expect(jwk?.use).toBe('sig');
  });

  it('does NOT leak private RSA components (d/p/q/dp/dq/qi) over the wire', async () => {
    const { publisher } = await makePublisher();
    const [jwk] = publisher.jwks().keys;
    expect(jwk?.d).toBeUndefined();
    expect(jwk?.p).toBeUndefined();
    expect(jwk?.q).toBeUndefined();
    expect(jwk?.dp).toBeUndefined();
    expect(jwk?.dq).toBeUndefined();
    expect(jwk?.qi).toBeUndefined();
  });
});
