import {
  type JwksDocument,
  OAuthGetJwksHandler,
} from '@app/o-auth/flows/application/get-jwks/o-auth-get-jwks.handler';
import { Test, TestingModule } from '@nestjs/testing';
import { OAuthGetJwksController } from './o-auth-get-jwks.controller';

const buildJwks = (overrides: Partial<JwksDocument['keys'][number]> = {}): JwksDocument => ({
  keys: [
    {
      kty: 'RSA',
      alg: 'RS256',
      use: 'sig',
      kid: 'deadbeefcafe0000',
      n: 'modulus-base64url',
      e: 'AQAB',
      ...overrides,
    },
  ],
});

describe('OAuthGetJwksController (transport — pure delegation)', () => {
  let controller: OAuthGetJwksController;
  let handler: { main: jest.Mock };

  beforeEach(async () => {
    handler = { main: jest.fn().mockReturnValue(buildJwks()) };

    const module: TestingModule = await Test.createTestingModule({
      controllers: [OAuthGetJwksController],
      providers: [{ provide: OAuthGetJwksHandler, useValue: handler }],
    }).compile();

    controller = module.get(OAuthGetJwksController);
  });

  it('returns the JWKS document exactly as the handler produces it', () => {
    const expected = buildJwks({ kid: 'specific-kid-1234', n: 'a-modulus' });
    handler.main.mockReturnValueOnce(expected);

    const result = controller.main();

    expect(result).toBe(expected);
  });

  it('invokes the handler exactly once per call (no caching at the controller)', () => {
    controller.main();
    controller.main();
    controller.main();
    expect(handler.main).toHaveBeenCalledTimes(3);
  });

  it('does NOT transform the JWKS shape (REST returns RFC 7517 verbatim)', () => {
    const fromHandler = buildJwks({
      kty: 'RSA',
      alg: 'RS256',
      use: 'sig',
      kid: 'abc123',
      n: 'mod',
      e: 'AQAB',
    });
    handler.main.mockReturnValueOnce(fromHandler);

    const result = controller.main();

    expect(result).toEqual(fromHandler);
    expect(Object.keys(result)).toEqual(['keys']);
  });
});
