/**
 * A4 — POST /device/enroll + /device/attest/challenge (fastify inject, mirrors test/api.test.ts).
 * Proves: a valid device:enroll bearer + valid P-256 CSR → 201 with a real X.509 leaf; missing /
 * invalid / wrong-right bearers → 401/403 (uniform); over-cap → 429; a malformed CSR → uniform
 * reject; the attest challenge stub returns a bound challenge. The bearer is verified through the
 * SAME injected `CapabilityVerifier` seam the admin API uses (boot/verifier.ts in production).
 */
import 'reflect-metadata'
import { describe, test, expect, beforeEach } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
import * as x509 from '@peculiar/x509'
import { webcrypto } from 'node:crypto'
import type { CapabilityToken, CapabilityRight } from 'relay-contracts'
import type { CapabilityVerifier } from '../src/api/authz.js'
import { buildCsrEc } from '../src/ca/csr-ec.js'
import { inProcessP256CaSigner } from '../src/boot/ca-wiring.js'
import { createDeviceLeafSigner } from '../src/ca/device-issue.js'
import { createDeviceRegistry, createMemoryDeviceStore } from '../src/registry/devices.js'
import {
  buildDeviceEnrollRouter,
  type DeviceEnrollDeps,
  type SubdomainOwnershipResolver,
} from '../src/api/device-enroll.js'
import { DEVICE_ENROLL_AUD } from '../src/auth/session.js'

x509.cryptoProvider.set(webcrypto)

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

// Fake verifier mirroring api.test.ts: 'enrollA'/'enrollB'→enroll right; 'attachA'→attach only; else reject.
const verifier: CapabilityVerifier = {
  async verify(raw, expectedAud, now): Promise<CapabilityToken> {
    const base = { aud: expectedAud, host: 'x', iat: now, exp: now + 600, jti: `jti-${raw}` }
    if (raw === 'enrollA') return { ...base, sub: ACCOUNT_A, rights: ['enroll'] as CapabilityRight[] }
    if (raw === 'enrollB') return { ...base, sub: ACCOUNT_B, rights: ['enroll'] as CapabilityRight[] }
    if (raw === 'attachA') return { ...base, sub: ACCOUNT_A, rights: ['attach'] as CapabilityRight[] }
    throw new Error('invalid token')
  },
}

// Ownership source of truth (host-onboarding registry in production). ACCOUNT_A owns 'alice' + 'bob';
// everything else is unclaimed → deny-by-default.
const SUBDOMAIN_OWNERS: Readonly<Record<string, string>> = { alice: ACCOUNT_A, bob: ACCOUNT_A }
const ownership: SubdomainOwnershipResolver = {
  async ownerOfSubdomain(sub) {
    return SUBDOMAIN_OWNERS[sub] ?? null
  },
}

async function csrBody(subdomain = 'alice'): Promise<Record<string, unknown>> {
  const { der } = await buildCsrEc('CN=web-terminal-device')
  return { csr: Buffer.from(der).toString('base64'), keyAlg: 'ec-p256', subdomain, deviceName: 'iphone' }
}

// The registry and the leaf signer MUST share ONE DeviceStore so the signer's gate finds the
// device the route just registered (mirrors host store sharing between registry + createRealLeafSigner).
function buildApp(opts: { deviceCap?: number; rateMax?: number } = {}): FastifyInstance {
  const ca = inProcessP256CaSigner()
  const store = createMemoryDeviceStore()
  const deps: DeviceEnrollDeps = {
    verifier,
    ownership,
    devices: createDeviceRegistry({ devices: store, deviceCap: opts.deviceCap ?? 5, rateMax: opts.rateMax ?? 50 }),
    signer: createDeviceLeafSigner({
      signer: ca,
      issuer: 'CN=device-CA',
      caChainDer: [ca.publicKeyRaw],
      sanBaseDomain: 'terminal.yaojia.wang',
      trustDomain: 'example.com',
      devices: store,
    }),
  }
  const app = Fastify({ logger: false })
  void app.register(buildDeviceEnrollRouter(deps))
  return app
}

let app: FastifyInstance
beforeEach(async () => {
  app = buildApp()
  await app.ready()
})

describe('A4 POST /device/enroll', () => {
  test('valid enroll bearer + valid P-256 CSR → 201 with a real cert', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody(),
    })
    expect(res.statusCode).toBe(201)
    const body = JSON.parse(res.body)
    expect(body.deviceId.length).toBeGreaterThan(0)
    expect(Array.isArray(body.caChain)).toBe(true)
    expect(typeof body.notAfter).toBe('string')
    expect(typeof body.renewAfter).toBe('string')
    // the returned cert is a real, re-parseable X.509 leaf
    const der = new Uint8Array(Buffer.from(body.cert, 'base64'))
    const leaf = new x509.X509Certificate(der)
    const san = leaf.getExtension(x509.SubjectAlternativeNameExtension)
    expect(san!.names.toJSON()).toContainEqual({ type: 'dns', value: 'alice.terminal.yaojia.wang' })
  })

  test('missing bearer → 401', async () => {
    const res = await app.inject({ method: 'POST', url: '/device/enroll', payload: await csrBody() })
    expect(res.statusCode).toBe(401)
  })

  test('invalid bearer → 401', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer bogus' },
      payload: await csrBody(),
    })
    expect(res.statusCode).toBe(401)
  })

  test('wrong-right bearer (attach, not enroll) → 403', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer attachA' },
      payload: await csrBody(),
    })
    expect(res.statusCode).toBe(403)
  })

  test('malformed body → 400 (Zod at the boundary)', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: { csr: '', keyAlg: 'rsa', subdomain: 'alice' },
    })
    expect(res.statusCode).toBe(400)
  })

  test('malformed CSR (valid shape, bad DER) → uniform reject 400', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: { csr: Buffer.from([0, 1, 2, 3]).toString('base64'), keyAlg: 'ec-p256', subdomain: 'alice', deviceName: 'x' },
    })
    expect(res.statusCode).toBe(400)
  })

  test('over per-account device cap → 429', async () => {
    const capped = buildApp({ deviceCap: 1, rateMax: 50 })
    await capped.ready()
    const ok = await capped.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('alice'),
    })
    expect(ok.statusCode).toBe(201)
    const over = await capped.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('bob'),
    })
    expect(over.statusCode).toBe(429)
  })

  test('over per-account rate-limit → 429', async () => {
    const limited = buildApp({ deviceCap: 50, rateMax: 1 })
    await limited.ready()
    const first = await limited.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('alice'),
    })
    expect(first.statusCode).toBe(201)
    const second = await limited.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('bob'),
    })
    expect(second.statusCode).toBe(429)
  })

  // ── Tenant-isolation gate (FIX C-native-3 / H-native-4) ──────────────────────────────────────────
  test('account B requesting account A\'s subdomain → 403, no cert issued', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollB' }, // valid enroll bearer for a DIFFERENT account
      payload: await csrBody('alice'), // owned by ACCOUNT_A
    })
    expect(res.statusCode).toBe(403)
    expect(JSON.parse(res.body).cert).toBeUndefined() // rejected before registration + issuance
  })

  test('unclaimed subdomain → 403 (uniform with foreign-owned: no existence oracle)', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('nobody'), // ACCOUNT_A does not own it
    })
    expect(res.statusCode).toBe(403)
  })

  test('reserved infra label (admin) → 400, never reaches a certificate SAN', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('admin'),
    })
    expect(res.statusCode).toBe(400)
  })

  test('subdomain that normalizes to an invalid label → 400', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('___'), // strips to empty → not a valid RFC-1123 label
    })
    expect(res.statusCode).toBe(400)
  })

  test('account A\'s own subdomain still enrolls (ownership gate does not affect the owner)', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/enroll',
      headers: { authorization: 'Bearer enrollA' },
      payload: await csrBody('alice'),
    })
    expect(res.statusCode).toBe(201)
  })
})

describe('A4 POST /device/attest/challenge (stub)', () => {
  test('valid bearer → 200 with a challenge + expires_in 120', async () => {
    const res = await app.inject({
      method: 'POST',
      url: '/device/attest/challenge',
      headers: { authorization: 'Bearer enrollA' },
    })
    expect(res.statusCode).toBe(200)
    const body = JSON.parse(res.body)
    expect(typeof body.challenge).toBe('string')
    expect(body.challenge.length).toBeGreaterThan(0)
    expect(body.expires_in).toBe(120)
  })

  test('missing bearer → 401', async () => {
    const res = await app.inject({ method: 'POST', url: '/device/attest/challenge' })
    expect(res.statusCode).toBe(401)
  })
})
