import { describe, it, expect, beforeEach } from 'vitest'
import { authorizeConnect, authorizeReattach } from '../src/authz/decide.js'
import { accountIdFromToken, AuthzInputError } from '../src/authz/principal.js'
import { resetDpopCacheForTest } from '../src/capability/verify.js'
import type { CapabilityToken } from 'relay-contracts'
import {
  setupP5SigningKey,
  makeHost,
  fakeHostRegistry,
  fakeSessionRegistry,
  fakeRevocationStore,
  issueWithDpop,
  uuid,
} from './_helpers.js'

const NOW = 1_700_000_000
const AUD_A = 'alice.term.example.com'

describe('deny-by-default authz (INV1/INV3/INV6)', () => {
  let signingKey: CryptoKey
  beforeEach(async () => {
    ;({ signingKey } = await setupP5SigningKey())
    resetDpopCacheForTest()
  })

  it('happy path: account A + own host + attach right + live host → ok', async () => {
    const hostA = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA)])
    const rev = fakeRevocationStore()
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostA, requiredRight: 'attach' },
      dpop,
      hosts,
      rev,
      NOW,
    )
    expect(out.ok).toBe(true)
    if (out.ok) {
      expect(out.hostId).toBe(hostA)
      expect(out.principal.accountId).toBe('acct-A')
      expect(out.jti.length).toBeGreaterThan(0)
    }
  })

  it('INV1 cross-tenant: A token but host owned by B → 403', async () => {
    const hostB = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-B', hostB)]) // host owned by B
    const rev = fakeRevocationStore()
    // A mints a token scoped to hostB (IDOR attempt) — sub=acct-A, host=hostB
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostB, aud: AUD_A, now: NOW })
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostB, requiredRight: 'attach' },
      dpop,
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant' })
  })

  it('accountIdFromToken returns sub; throws on empty sub', () => {
    const tok = { sub: 'acct-A' } as CapabilityToken
    expect(accountIdFromToken(tok)).toBe('acct-A')
    expect(() => accountIdFromToken({ sub: '' } as CapabilityToken)).toThrow(AuthzInputError)
  })

  it('INV6 reattach cross-tenant: valid host-A token but session owned by B → 403', async () => {
    const hostA = uuid()
    const sessionB = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA)])
    const sessions = fakeSessionRegistry([{ sessionId: sessionB, hostId: uuid(), accountId: 'acct-B' }])
    const rev = fakeRevocationStore()
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await authorizeReattach(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostA, requiredRight: 'attach', sessionId: sessionB },
      dpop,
      hosts,
      sessions,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'cross_tenant_session' })
  })

  it('missing/invalid token → 401', async () => {
    const hosts = fakeHostRegistry([])
    const rev = fakeRevocationStore()
    const out = await authorizeConnect(
      { capabilityRaw: 'garbage', expectedAud: AUD_A, requestedHostId: uuid(), requiredRight: 'attach' },
      { proofJws: 'x.y.z', htu: 'h', htm: 'GET' },
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 401 })
  })

  it('failing DPoP proof (PoP mismatch) → 401', async () => {
    const hostA = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA)])
    const rev = fakeRevocationStore()
    const { raw } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostA, requiredRight: 'attach' },
      { proofJws: 'a.b.c', htu: 'h', htm: 'GET' }, // bogus proof
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 401, reason: 'dpop_proof_failed' })
  })

  it('revoked jti → 403', async () => {
    const hostA = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA)])
    const rev = fakeRevocationStore()
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    // revoke the token's jti
    const { verifyCapabilityToken } = await import('../src/capability/verify.js')
    const tok = await verifyCapabilityToken(raw, AUD_A, NOW)
    await rev.revokeJti(tok.jti, tok.exp)
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostA, requiredRight: 'attach' },
      dpop,
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'token_revoked' })
  })

  it('requiredRight=kill with attach-only token → 403', async () => {
    const hostA = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA)])
    const rev = fakeRevocationStore()
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, rights: ['attach'], now: NOW })
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostA, requiredRight: 'kill' },
      dpop,
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'insufficient_rights' })
  })

  it('token.host !== requestedHostId (path-swap IDOR) → 403', async () => {
    const hostA = uuid()
    const otherHost = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA), makeHost('acct-A', otherHost)])
    const rev = fakeRevocationStore()
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: otherHost, requiredRight: 'attach' },
      dpop,
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'host_scope_mismatch' })
  })

  it('revoked host status → 403', async () => {
    const hostA = uuid()
    const hosts = fakeHostRegistry([makeHost('acct-A', hostA, 'revoked')])
    const rev = fakeRevocationStore()
    const { raw, dpop } = await issueWithDpop(signingKey, { accountId: 'acct-A', host: hostA, aud: AUD_A, now: NOW })
    const out = await authorizeConnect(
      { capabilityRaw: raw, expectedAud: AUD_A, requestedHostId: hostA, requiredRight: 'attach' },
      dpop,
      hosts,
      rev,
      NOW,
    )
    expect(out).toMatchObject({ ok: false, status: 403, reason: 'host_revoked' })
  })
})
