import { describe, test, expect, beforeEach } from 'vitest'
import type { FastifyInstance } from 'fastify'
import { createMemoryStores } from '../src/store/memory.js'
import { createHostRegistry } from '../src/registry/hosts.js'
import { buildControlPlane } from '../src/main.js'
import { loadEnv } from '../src/env.js'
import { fingerprint } from '../src/ca/fingerprint.js'
import { generateEd25519 } from '../src/util/crypto.js'
import { bytesToBase64 } from '../src/util/bytes.js'
import type { CapabilityVerifier } from '../src/api/authz.js'
import type { CapabilityToken, CapabilityRight } from 'relay-contracts'
import type { Stores } from '../src/store/ports.js'

const ACCOUNT_A = '11111111-1111-4111-8111-111111111111'
const ACCOUNT_B = '22222222-2222-4222-8222-222222222222'

const env = loadEnv({
  PG_URL: 'postgres://u:p@localhost:5432/cp',
  REDIS_URL: 'redis://localhost:6379',
  CAPABILITY_SIGN_PUBKEY_B64: bytesToBase64(new Uint8Array(32).fill(1)),
  CA_INTERMEDIATE_KMS_KEY_REF: 'kms://key/intermediate',
  CA_INTERMEDIATE_CERT_PATH: '/etc/cp/int.pem',
  NODE_MTLS_TRUST_BUNDLE_PATH: '/etc/cp/node-ca.pem',
  BASE_DOMAIN: 'term.example.com',
})

// Fake P5 verifier: 'tokenA'→account A (manage), 'attachA'→account A (attach only). Else reject.
// Async to match the `CapabilityVerifier` seam (real §4.3 verify is async).
const verifier: CapabilityVerifier = {
  async verify(raw, expectedAud, now): Promise<CapabilityToken> {
    const base = { aud: expectedAud, host: 'x', iat: now, exp: now + 3600, jti: `jti-${raw}` }
    if (raw === 'tokenA') return { ...base, sub: ACCOUNT_A, rights: ['manage'] as CapabilityRight[] }
    if (raw === 'attachA') return { ...base, sub: ACCOUNT_A, rights: ['attach'] as CapabilityRight[] }
    throw new Error('invalid token')
  },
}

let app: FastifyInstance
let stores: Stores
let hostOfB: string

beforeEach(async () => {
  stores = createMemoryStores()
  const built = await buildControlPlane(env, { stores, verifier })
  app = built.app
  await app.ready()
  // Bind a host owned by account B directly.
  const hosts = createHostRegistry({ hosts: stores.hosts })
  const { publicKeyRaw } = generateEd25519()
  const host = await hosts.bindHost({ accountId: ACCOUNT_B, subdomain: 'bob', agentPubkey: publicKeyRaw, enrollFpr: fingerprint(publicKeyRaw) })
  hostOfB = host.hostId
})

describe('T11 provisioning API (INV3/INV1/INV6)', () => {
  test('HEADLINE: account A with forged {account_id:B} deleting B-owned host → 403', async () => {
    const res = await app.inject({
      method: 'DELETE',
      url: `/hosts/${hostOfB}`,
      headers: { authorization: 'Bearer tokenA' },
      payload: { account_id: ACCOUNT_B }, // forged — must be ignored
    })
    expect(res.statusCode).toBe(403)
  })

  test('missing token → 401', async () => {
    const res = await app.inject({ method: 'DELETE', url: `/hosts/${hostOfB}` })
    expect(res.statusCode).toBe(401)
  })

  test('attach-scoped token cannot hit a manage route → 403', async () => {
    const res = await app.inject({ method: 'DELETE', url: `/hosts/${hostOfB}`, headers: { authorization: 'Bearer attachA' } })
    expect(res.statusCode).toBe(403)
  })

  test('owner CAN deprovision its own host → 204', async () => {
    // give A its own host
    const hosts = createHostRegistry({ hosts: stores.hosts })
    const { publicKeyRaw } = generateEd25519()
    const own = await hosts.bindHost({ accountId: ACCOUNT_A, subdomain: 'alice', agentPubkey: publicKeyRaw, enrollFpr: fingerprint(publicKeyRaw) })
    const res = await app.inject({ method: 'DELETE', url: `/hosts/${own.hostId}`, headers: { authorization: 'Bearer tokenA' } })
    expect(res.statusCode).toBe(204)
    expect((await stores.hosts.get(own.hostId))?.status).toBe('revoked')
  })

  test('pairing-code route scoped to own account; foreign :id → 403', async () => {
    const ok = await app.inject({ method: 'POST', url: `/accounts/${ACCOUNT_A}/pairing-codes`, headers: { authorization: 'Bearer tokenA' } })
    expect(ok.statusCode).toBe(201)
    expect(JSON.parse(ok.body).code).toBeDefined()
    const foreign = await app.inject({ method: 'POST', url: `/accounts/${ACCOUNT_B}/pairing-codes`, headers: { authorization: 'Bearer tokenA' } })
    expect(foreign.statusCode).toBe(403)
  })

  test('malformed enroll body → 400 (Zod at the boundary)', async () => {
    const res = await app.inject({ method: 'POST', url: '/enroll', payload: { code: '' } })
    expect(res.statusCode).toBe(400)
  })
})
