import { describe, test, expect, beforeEach } from 'vitest'
import type { FastifyInstance } from 'fastify'
import { createMemoryStores } from '../src/store/memory.js'
import { buildControlPlane } from '../src/main.js'
import { loadEnv } from '../src/env.js'
import { generateEd25519 } from '../src/util/crypto.js'
import { buildCsr } from '../src/ca/csr.js'
import { bytesToBase64 } from '../src/util/bytes.js'
import { nodeIdentityFromRequest, type RequestWithTls } from '../src/node-auth/identity.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 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',
})

const verifier: CapabilityVerifier = {
  async verify(raw, expectedAud, now): Promise<CapabilityToken> {
    if (raw !== 'tokenA') throw new Error('invalid token')
    return { sub: ACCOUNT_A, aud: expectedAud, host: 'x', rights: ['manage'] as CapabilityRight[], iat: now, exp: now + 3600, jti: 'jti-A' }
  },
}

let app: FastifyInstance
let stores: Stores

beforeEach(async () => {
  stores = createMemoryStores()
  const built = await buildControlPlane(env, { stores, verifier })
  app = built.app
  await app.ready()
})

const auth = { authorization: 'Bearer tokenA' }

describe('T11 provisioning API — remaining routes', () => {
  test('POST /accounts creates an account (201)', async () => {
    const res = await app.inject({ method: 'POST', url: '/accounts', headers: auth, payload: { plan: 'pro' } })
    expect(res.statusCode).toBe(201)
    expect(JSON.parse(res.body).plan).toBe('pro')
  })

  test('POST /accounts/:id/status suspends own account', async () => {
    // must be the caller's own account id (A) — create A explicitly in store
    const { createAccountRegistry } = await import('../src/registry/accounts.js')
    const reg = createAccountRegistry({ accounts: stores.accounts })
    await stores.accounts.insert({ accountId: ACCOUNT_A, plan: 'free', createdAt: new Date().toISOString(), status: 'active' })
    void reg
    const res = await app.inject({ method: 'POST', url: `/accounts/${ACCOUNT_A}/status`, headers: auth, payload: { status: 'suspended' } })
    expect(res.statusCode).toBe(200)
    expect(JSON.parse(res.body).status).toBe('suspended')
  })

  test('GET /accounts/:id/hosts returns ownership-scoped list', async () => {
    const res = await app.inject({ method: 'GET', url: `/accounts/${ACCOUNT_A}/hosts`, headers: auth })
    expect(res.statusCode).toBe(200)
    expect(Array.isArray(JSON.parse(res.body))).toBe(true)
  })

  test('end-to-end enroll: issue code then POST /enroll → 201 EnrollResult', async () => {
    const issued = await app.inject({ method: 'POST', url: `/accounts/${ACCOUNT_A}/pairing-codes`, headers: auth })
    const code = JSON.parse(issued.body).code as string
    const { publicKeyRaw, privateKey } = generateEd25519()
    const res = await app.inject({
      method: 'POST',
      url: '/enroll',
      payload: {
        code,
        agentPubkey: bytesToBase64(publicKeyRaw),
        csr: bytesToBase64(buildCsr(privateKey, publicKeyRaw)),
      },
    })
    expect(res.statusCode).toBe(201)
    const body = JSON.parse(res.body)
    expect(body.subdomain).toBeDefined()
    expect(body.cert).toContain('BEGIN CERTIFICATE')
    expect(typeof body.hostContentSecret).toBe('string')
  })
})

describe('T9 nodeIdentityFromRequest wrapper', () => {
  test('derives nodeId from an authorized TLS peer cert subject CN', () => {
    const req: RequestWithTls = {
      socket: { authorized: true, getPeerCertificate: () => ({ subject: { CN: 'spiffe://relay/node-7' } }) },
    }
    expect(nodeIdentityFromRequest(req).nodeId).toBe('spiffe://relay/node-7')
  })

  test('unauthenticated socket → 401', () => {
    const req: RequestWithTls = { socket: { authorized: false, getPeerCertificate: () => undefined } }
    expect(() => nodeIdentityFromRequest(req)).toThrow(/mutually authenticated/)
  })
})
