import { test } from 'node:test';
import assert from 'node:assert/strict';
import { getOidcIssuer, AutoDiscoveryInfo } from './cs-api';

const info = (extra: Record<string, unknown>): AutoDiscoveryInfo =>
  ({ 'm.homeserver': { base_url: 'https://hs' }, ...extra }) as AutoDiscoveryInfo;

test('getOidcIssuer reads the stable m.authentication key', () => {
  assert.deepEqual(
    getOidcIssuer(info({ 'm.authentication': { issuer: 'https://i', account: 'https://a' } })),
    { issuer: 'https://i', account: 'https://a' },
  );
});

test('getOidcIssuer falls back to the unstable msc2965 key', () => {
  assert.deepEqual(
    getOidcIssuer(info({ 'org.matrix.msc2965.authentication': { issuer: 'https://u' } })),
    { issuer: 'https://u', account: undefined },
  );
});

test('getOidcIssuer prefers stable over unstable when both present', () => {
  assert.equal(
    getOidcIssuer(
      info({
        'm.authentication': { issuer: 'https://stable' },
        'org.matrix.msc2965.authentication': { issuer: 'https://unstable' },
      }),
    ).issuer,
    'https://stable',
  );
});

test('getOidcIssuer returns {} for non-OIDC servers', () => {
  assert.deepEqual(getOidcIssuer(info({})), {});
  assert.deepEqual(getOidcIssuer(info({ 'm.authentication': {} })), {}); // present but no issuer
});
