/**
 * A4 (session subsystem, FIX C-native-1) — the minimal device:enroll token mint/verify + the login
 * stub seam. Proves: a minted token round-trips through relay-auth's REAL §4.3 verifier; a token
 * lacking the 'enroll' right is rejected (403); a wrong audience is rejected (401); an expired token
 * is rejected (401); and the single-tenant login stub resolves a credential → accountId (deny-by-default
 * on a wrong / empty credential).
 */
import { describe, test, expect, beforeEach } from 'vitest'
import { configureVerifyKey } from 'relay-auth'
import { resetVerifyKeyForTest } from 'relay-auth/src/config/keys.js'
import { generateEd25519KeyPair } from 'relay-auth/src/crypto/ed25519.js'
import { signPaseto } from 'relay-auth/src/crypto/paseto.js'
import { randomBytes } from 'node:crypto'
import {
  mintDeviceEnrollToken,
  verifyDeviceEnrollToken,
  loginToAccountId,
  requireEnrollRight,
  DeviceEnrollAuthError,
  DEVICE_ENROLL_AUD,
} from '../src/auth/session.js'

const NOW = 1_700_000_000
const ACCOUNT_A = '11111111-1111-4111-8111-111111111111'

/** 43-char base64url placeholder (satisfies the shared §4.3 verifier's `cnf.jkt` requirement). */
function jkt(): string {
  return Buffer.from(randomBytes(32)).toString('base64url')
}

let signingKey: CryptoKey

beforeEach(async () => {
  resetVerifyKeyForTest()
  const pair = await generateEd25519KeyPair()
  await configureVerifyKey(pair.publicKey)
  signingKey = pair.privateKey
})

describe('A4 device:enroll session token', () => {
  test('mint → verify round-trips and yields the accountId (rights:[enroll])', async () => {
    const raw = await mintDeviceEnrollToken(ACCOUNT_A, { signingKey, now: NOW })
    const { accountId } = await verifyDeviceEnrollToken(raw, { now: NOW + 5 })
    expect(accountId).toBe(ACCOUNT_A)
  })

  test('a token missing the enroll right is rejected (403)', async () => {
    // Mint an otherwise-valid device-enroll-aud token but with rights:['attach'] (no enroll).
    const body = {
      sub: ACCOUNT_A,
      aud: DEVICE_ENROLL_AUD,
      host: 'device-enroll',
      rights: ['attach'],
      iat: NOW,
      exp: NOW + 600,
      jti: 'jti-noenroll',
      cnf: { jkt: jkt() },
    }
    const raw = await signPaseto(body, signingKey)
    await expect(verifyDeviceEnrollToken(raw, { now: NOW + 5 })).rejects.toMatchObject({ status: 403 })
  })

  test('a token with the wrong audience is rejected (401)', async () => {
    const raw = await mintDeviceEnrollToken(ACCOUNT_A, { signingKey, now: NOW, aud: 'not-device-enroll' })
    await expect(verifyDeviceEnrollToken(raw, { now: NOW + 5 })).rejects.toMatchObject({ status: 401 })
  })

  test('an expired token is rejected (401)', async () => {
    const raw = await mintDeviceEnrollToken(ACCOUNT_A, { signingKey, now: NOW, ttlSeconds: 60 })
    await expect(verifyDeviceEnrollToken(raw, { now: NOW + 120 })).rejects.toMatchObject({ status: 401 })
  })

  test('a garbage token is rejected (401), uniform reject', async () => {
    await expect(verifyDeviceEnrollToken('not-a-token', { now: NOW })).rejects.toBeInstanceOf(DeviceEnrollAuthError)
  })

  test('requireEnrollRight throws 403 without enroll, passes with it', () => {
    const base = { sub: ACCOUNT_A, aud: DEVICE_ENROLL_AUD, host: 'x', iat: NOW, exp: NOW + 1, jti: 'j' }
    expect(() => requireEnrollRight({ ...base, rights: ['attach'] })).toThrow(DeviceEnrollAuthError)
    expect(() => requireEnrollRight({ ...base, rights: ['enroll'] })).not.toThrow()
  })

  test('ttl is minutes-scale (separate from the 30–60s connect clamp)', async () => {
    // A 10-minute token must still verify well past the 60s connect clamp horizon.
    const raw = await mintDeviceEnrollToken(ACCOUNT_A, { signingKey, now: NOW })
    const { accountId } = await verifyDeviceEnrollToken(raw, { now: NOW + 5 * 60 })
    expect(accountId).toBe(ACCOUNT_A)
  })
})

describe('A4 loginToAccountId stub seam (single-tenant MVP)', () => {
  test('resolves an operator credential → accountId', () => {
    const acct = loginToAccountId('op-secret', { operatorCredential: 'op-secret', accountId: ACCOUNT_A })
    expect(acct).toBe(ACCOUNT_A)
  })

  test('rejects a wrong credential (401)', () => {
    expect(() => loginToAccountId('wrong', { operatorCredential: 'op-secret', accountId: ACCOUNT_A })).toThrow(
      DeviceEnrollAuthError,
    )
  })

  test('rejects an empty credential (401)', () => {
    expect(() => loginToAccountId('', { operatorCredential: 'op-secret', accountId: ACCOUNT_A })).toThrow(
      DeviceEnrollAuthError,
    )
  })

  test('supports an injected resolver seam (real login layer later)', () => {
    const acct = loginToAccountId('pairing-xyz', { resolve: (c) => (c === 'pairing-xyz' ? ACCOUNT_A : null) })
    expect(acct).toBe(ACCOUNT_A)
  })

  test('rejects when not configured (deny-by-default)', () => {
    expect(() => loginToAccountId('anything', {})).toThrow(DeviceEnrollAuthError)
  })
})
