import { describe, it, expect, beforeEach } from 'vitest'
import { onUpgrade, onReattach, type EnforceDeps, type UpgradeContext } from '../src/index.js'
import { verifyCapabilityToken, resetDpopCacheForTest } from '../src/capability/verify.js'
import { needsStepUp } from '../src/human/stepup/stepup.js'
import type { StepUpPolicy } from '../src/types.js'
import {
  setupP5SigningKey,
  makeHost,
  principal,
  fakeHostRegistry,
  fakeSessionRegistry,
  fakeRevocationStore,
  fakeTokenBucket,
  fakeAuditSink,
  issueWithDpop,
  uuid,
} from './_helpers.js'

const NOW = 1_700_000_000
const AUD_A = 'alice.term.example.com'
const ORIGIN_A = `https://${AUD_A}`
const ALLOWED = [ORIGIN_A]
const NEVER_REQUIRED: StepUpPolicy = { required: false, maxAgeSeconds: Number.MAX_SAFE_INTEGER, requiredMethod: 'passkey' }

describe('enforcement onUpgrade/onReattach (T12)', () => {
  let signingKey: CryptoKey
  let hostA: string
  let deps: EnforceDeps
  let rev: ReturnType<typeof fakeRevocationStore>
  let audit: ReturnType<typeof fakeAuditSink>

  beforeEach(async () => {
    ;({ signingKey } = await setupP5SigningKey())
    resetDpopCacheForTest()
    hostA = uuid()
    rev = fakeRevocationStore()
    audit = fakeAuditSink()
    deps = {
      hosts: fakeHostRegistry([makeHost('acct-A', hostA)]),
      sessions: fakeSessionRegistry([]),
      revocation: rev,
      buckets: fakeTokenBucket(),
      audit,
      stepUpPolicyFor: () => NEVER_REQUIRED,
    }
  })

  function ctxFor(bundle: { raw: string; dpop: UpgradeContext['dpop'] }, over: Partial<UpgradeContext> = {}): UpgradeContext {
    return {
      capabilityRaw: bundle.raw,
      originHeader: ORIGIN_A,
      expectedAud: AUD_A,
      requestedHostId: hostA,
      requiredRight: 'attach',
      remoteAddrHash: 'ip-hash',
      activeSessionCount: 0,
      dpop: bundle.dpop,
      principal: null,
      ...over,
    }
  }

  it('foreign Origin → 401 even with a valid token (INV15 retained)', async () => {
    const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await onUpgrade(ctxFor(b, { originHeader: 'https://evil.com' }), deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 401, reason: 'bad_origin' })
    expect(audit.events).toHaveLength(1)
    expect(audit.events[0]!.outcome).toBe('deny')
  })

  it('valid Origin, no/garbage token → 401', async () => {
    const out = await onUpgrade(ctxFor({ raw: 'garbage', dpop: { proofJws: 'a.b.c', htu: 'h', htm: 'GET' } }), deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 401 })
  })

  it('cross-tenant (A token, host B) → 403 with exactly one cross-tenant-attempt audit event', async () => {
    const hostB = uuid()
    deps = { ...deps, hosts: fakeHostRegistry([makeHost('acct-B', hostB)]) }
    const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostB, aud: AUD_A, now: NOW })
    const out = await onUpgrade(ctxFor(b, { requestedHostId: hostB }), deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant' })
    expect(audit.events).toHaveLength(1)
    expect(audit.events[0]!.action).toBe('cross-tenant-attempt')
  })

  it('pre-auth throttle fires BEFORE token verification (Finding-5)', async () => {
    const buckets = fakeTokenBucket()
    buckets.blocked.add('preauth:ip:ip-hash')
    deps = { ...deps, buckets }
    // even a totally invalid token is thrown out at the pre-auth stage
    const out = await onUpgrade(ctxFor({ raw: 'garbage', dpop: { proofJws: 'a.b.c', htu: 'h', htm: 'GET' } }), deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'pre_auth_throttled' })
  })

  it('per-account rate-limited → deny', async () => {
    const buckets = fakeTokenBucket()
    buckets.blocked.add('connect:acct:acct-A')
    deps = { ...deps, buckets }
    const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await onUpgrade(ctxFor(b), deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'rate_limited' })
  })

  it('replayed single-use token (jti already consumed) → 403 token_replayed', async () => {
    const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const tok = await verifyCapabilityToken(b.raw, AUD_A, NOW)
    await rev.consumeOnce(tok.jti, tok.exp) // pre-consume
    const out = await onUpgrade(ctxFor(b), deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'token_replayed' })
  })

  it('happy path → ok:true with an allow audit event', async () => {
    const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await onUpgrade(ctxFor(b), deps, ALLOWED, NOW)
    expect(out.ok).toBe(true)
    expect(audit.events).toHaveLength(1)
    expect(audit.events[0]!.outcome).toBe('allow')
    expect(audit.events[0]!.action).toBe('attach')
  })

  it('reattach to a foreign session → 403', async () => {
    const sessionB = uuid()
    deps = { ...deps, sessions: fakeSessionRegistry([{ sessionId: sessionB, hostId: uuid(), accountId: 'acct-B' }]) }
    const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await onReattach({ ...ctxFor(b), sessionId: sessionB }, deps, ALLOWED, NOW)
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant_session' })
  })

  describe('v0.10 step-up augmentation (Finding-3, F1/F2)', () => {
    const STRICT: StepUpPolicy = { required: true, maxAgeSeconds: 300, requiredMethod: 'passkey' }

    it('fresh login but stale step-up → 403 step_up_required at onUpgrade', async () => {
      deps = { ...deps, stepUpPolicyFor: () => STRICT }
      const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
      const freshLogin = principal('acct-A', { authAt: NOW, stepUpAt: null, amr: ['passkey'] })
      const out = await onUpgrade(ctxFor(b, { principal: freshLogin }), deps, ALLOWED, NOW)
      expect(out).toMatchObject({ ok: false, status: 403, reason: 'step_up_required' })
      expect(audit.events.some((e) => e.action === 'stepup' && e.outcome === 'deny')).toBe(true)
    })

    it('after a fresh step-up the same request → ok:true', async () => {
      deps = { ...deps, stepUpPolicyFor: () => STRICT }
      const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
      const steppedUp = principal('acct-A', { authAt: NOW, stepUpAt: NOW, amr: ['passkey', 'stepup'], stepUpMethod: 'passkey' })
      expect(needsStepUp(steppedUp, STRICT, NOW)).toBe(false)
      const out = await onUpgrade(ctxFor(b, { principal: steppedUp }), deps, ALLOWED, NOW)
      expect(out.ok).toBe(true)
    })

    it('STRICT (required) policy + principal:null → 403 step_up_required (F2 fail-closed)', async () => {
      deps = { ...deps, stepUpPolicyFor: () => STRICT }
      const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
      const out = await onUpgrade(ctxFor(b, { principal: null }), deps, ALLOWED, NOW)
      expect(out).toMatchObject({ ok: false, status: 403, reason: 'step_up_required' })
      expect(audit.events.some((e) => e.action === 'stepup' && e.outcome === 'deny')).toBe(true)
    })

    it('required:false policy + principal:null → allow (non-step-up host preserved)', async () => {
      deps = { ...deps, stepUpPolicyFor: () => NEVER_REQUIRED }
      const b = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
      const out = await onUpgrade(ctxFor(b, { principal: null }), deps, ALLOWED, NOW)
      expect(out.ok).toBe(true)
      expect(audit.events.some((e) => e.outcome === 'allow')).toBe(true)
    })
  })
})
