import { describe, it, expect } from 'vitest';
import { mkdtempSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { Repository } from '../../db/repository.js';
import { buildA2aOidcConfig } from './oidc-config.js';

function deps() {
  const dir = mkdtempSync(join(tmpdir(), 'a2a-cfg-'));
  return { repo: new Repository(':memory:'), secretsDir: dir, resourceAudience: 'https://maestro.test/a2a', cookieKeys: ['k1'] };
}

describe('buildA2aOidcConfig', () => {
  it('declares the a2a.read scope and enables introspection/revocation', () => {
    const cfg = buildA2aOidcConfig(deps());
    expect(cfg.scopes).toContain('a2a.read');
    expect(cfg.features?.introspection?.enabled).toBe(true);
    expect(cfg.features?.revocation?.enabled).toBe(true);
    expect(cfg.features?.resourceIndicators?.enabled).toBe(true);
  });

  it('requires PKCE for all clients', () => {
    const cfg = buildA2aOidcConfig(deps());
    expect(cfg.pkce?.required?.({} as any, {} as any)).toBe(true);
  });

  it('getResourceServerInfo returns the configured audience with a2a.read scope', () => {
    const d = deps();
    const cfg = buildA2aOidcConfig(d);
    const info = cfg.features!.resourceIndicators!.getResourceServerInfo!(
      {} as any, 'https://maestro.test/a2a', {} as any,
    );
    expect(info).toMatchObject({ audience: 'https://maestro.test/a2a', scope: expect.stringContaining('a2a.read') });
  });

  it('findAccount echoes the accountId set during the login interaction', async () => {
    const cfg = buildA2aOidcConfig(deps());
    const acct = await cfg.findAccount!({} as any, 'user-123');
    expect(acct?.accountId).toBe('user-123');
    expect(await acct?.claims()).toMatchObject({ sub: 'user-123' });
  });
});
