import { describe, it, expect } from 'vitest'
import { generateKeyPairSync, createSign, type webcrypto } from 'node:crypto'
import { encodeBase64UrlBytes } from 'relay-contracts'
import {
  buildAuthUrl,
  verifyIdToken,
  pkceChallenge,
  randomUrlToken,
  OidcError,
  type OidcConfig,
} from '../src/human/oidc/oidc.js'

const NOW = 1_700_000_000

// RS256 test key
const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })
const jwk = publicKey.export({ format: 'jwk' }) as webcrypto.JsonWebKey & { kid?: string }
jwk.kid = 'test-key'

function b64u(obj: unknown): string {
  return encodeBase64UrlBytes(new TextEncoder().encode(JSON.stringify(obj)))
}

function signIdToken(claims: Record<string, unknown>): string {
  const header = { alg: 'RS256', kid: 'test-key', typ: 'JWT' }
  const signingInput = `${b64u(header)}.${b64u(claims)}`
  const sig = createSign('RSA-SHA256').update(signingInput).sign(privateKey)
  return `${signingInput}.${encodeBase64UrlBytes(new Uint8Array(sig))}`
}

const cfg: OidcConfig = {
  issuer: 'https://idp.example.com',
  clientId: 'relay-client',
  redirectUri: 'https://relay.example.com/cb',
  scopes: ['openid', 'email'],
  authorizationEndpoint: 'https://idp.example.com/authorize',
  tokenEndpoint: 'https://idp.example.com/token',
  jwks: [jwk],
  allowedIssuers: ['https://idp.example.com'],
  resolveAccount: async (iss, sub) => `acct-for-${iss}-${sub}`,
}

describe('OIDC SSO (T7, PKCE)', () => {
  it('buildAuthUrl carries PKCE S256 + state + nonce', () => {
    const url = new URL(buildAuthUrl(cfg, 'st', 'no', pkceChallenge(randomUrlToken())))
    expect(url.searchParams.get('code_challenge_method')).toBe('S256')
    expect(url.searchParams.get('state')).toBe('st')
    expect(url.searchParams.get('nonce')).toBe('no')
    expect(url.searchParams.get('response_type')).toBe('code')
  })

  it('verifies a valid id_token → OidcIdentity mapped to the team account', async () => {
    const idToken = signIdToken({
      iss: cfg.issuer,
      aud: cfg.clientId,
      sub: 'user-1',
      exp: NOW + 300,
      nonce: 'expected-nonce',
    })
    const identity = await verifyIdToken(cfg, idToken, 'expected-nonce', NOW)
    expect(identity).toEqual({
      issuer: cfg.issuer,
      subject: 'user-1',
      accountId: 'acct-for-https://idp.example.com-user-1',
    })
  })

  it('rejects a nonce mismatch (replay)', async () => {
    const idToken = signIdToken({ iss: cfg.issuer, aud: cfg.clientId, sub: 'u', exp: NOW + 300, nonce: 'a' })
    await expect(verifyIdToken(cfg, idToken, 'b', NOW)).rejects.toThrow(OidcError)
  })

  it('rejects an expired id_token', async () => {
    const idToken = signIdToken({ iss: cfg.issuer, aud: cfg.clientId, sub: 'u', exp: NOW - 1, nonce: 'n' })
    await expect(verifyIdToken(cfg, idToken, 'n', NOW)).rejects.toThrow('expired')
  })

  it('rejects an unknown issuer (not in allow-list)', async () => {
    const idToken = signIdToken({ iss: 'https://evil.example', aud: cfg.clientId, sub: 'u', exp: NOW + 5, nonce: 'n' })
    await expect(verifyIdToken(cfg, idToken, 'n', NOW)).rejects.toThrow('issuer')
  })

  it('rejects an aud mismatch', async () => {
    const idToken = signIdToken({ iss: cfg.issuer, aud: 'someone-else', sub: 'u', exp: NOW + 5, nonce: 'n' })
    await expect(verifyIdToken(cfg, idToken, 'n', NOW)).rejects.toThrow('aud')
  })

  it('rejects a tampered signature', async () => {
    const idToken = signIdToken({ iss: cfg.issuer, aud: cfg.clientId, sub: 'u', exp: NOW + 5, nonce: 'n' })
    const tampered = idToken.slice(0, -4) + (idToken.endsWith('AAAA') ? 'BBBB' : 'AAAA')
    await expect(verifyIdToken(cfg, tampered, 'n', NOW)).rejects.toThrow(OidcError)
  })
})
