import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { describe, it, expect } from 'vitest'
import { spiffeIdFor, parseSpiffeId, SpiffeError } from '../src/agent/spiffe.js'
import {
  verifyAgentCert,
  defaultParseX509,
  splitPemBundle,
  type ParsedCert,
} from '../src/agent/verify-mtls.js'
import { shouldRotate, DEFAULT_ROTATION_PLAN } from '../src/agent/rotate.js'
import { fakeHostRegistry, makeHost } from './_helpers.js'

const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'mtls')
const readFixture = (name: string): string => readFileSync(join(FIXTURES, name), 'utf8')

const NOW = 1_700_000_000
const DOMAIN = 'example.com'

function certParser(cert: ParsedCert) {
  return () => cert
}

describe('SPIFFE-ID scheme (T9)', () => {
  it('formats and round-trips account/host', () => {
    const id = spiffeIdFor('acct-A', 'host-1', DOMAIN)
    expect(id).toBe('spiffe://relay.example.com/account/acct-A/host/host-1')
    expect(parseSpiffeId(id)).toEqual({ accountId: 'acct-A', id: 'host-1', kind: 'host' })
  })

  it('rejects a path-traversal / wildcard SPIFFE-ID', () => {
    expect(() => parseSpiffeId('spiffe://relay.example.com/account/../host/x')).toThrow()
    expect(() => parseSpiffeId('spiffe://relay.example.com/account/*/host/x')).toThrow(SpiffeError)
  })
})

describe('agent cert verification (INV4/INV14)', () => {
  const enrolled = spiffeIdFor('acct-A', 'host-1', DOMAIN)
  const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
  const validCert: ParsedCert = {
    spiffeUri: enrolled,
    notBefore: NOW - 10,
    notAfter: NOW + 3600,
    chainValid: true,
  }

  it('accepts an enrolled, in-date, chain-valid cert', async () => {
    const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(validCert))
    expect(r).toMatchObject({ ok: true, hostId: 'host-1', accountId: 'acct-A' })
  })

  it('refuses a SPIFFE-ID whose host is not in the registry (INV4)', async () => {
    const cert = { ...validCert, spiffeUri: spiffeIdFor('acct-A', 'host-unknown', DOMAIN) }
    const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
    expect(r).toMatchObject({ ok: false, reason: 'host_not_enrolled' })
  })

  it('refuses an expired leaf', async () => {
    const cert = { ...validCert, notAfter: NOW - 1 }
    const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
    expect(r).toMatchObject({ ok: false, reason: 'expired' })
  })

  it('refuses a SPIFFE-ID account mismatch (cert account ≠ registry account)', async () => {
    const cert = { ...validCert, spiffeUri: spiffeIdFor('acct-B', 'host-1', DOMAIN) }
    const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
    expect(r).toMatchObject({ ok: false, reason: 'spiffe_account_mismatch' })
  })

  it('refuses a chain that does not verify against the CA', async () => {
    const cert = { ...validCert, chainValid: false }
    const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
    expect(r).toMatchObject({ ok: false, reason: 'chain_invalid' })
  })

  it('refuses a device-kind cert on the host channel even if the id collides with an enrolled host (kind guard)', async () => {
    // Trust-broadening guard: a /device/ SAN whose id happens to equal an enrolled hostId
    // (same account) must NOT be accepted by the host-agent verifier. The host channel is
    // host-only; device certs are enforced at nginx :8470, not here.
    const cert = { ...validCert, spiffeUri: spiffeIdFor('acct-A', 'host-1', DOMAIN, 'device') }
    const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
    expect(r).toMatchObject({ ok: false, reason: 'not_host_cert' })
  })
})

describe('defaultParseX509 real X.509 path validation (INV4/INV14)', () => {
  const leafPem = readFixture('leaf.pem')
  const caChainPem = readFixture('ca-chain.pem') // intermediate + root
  const rootPem = readFixture('root.pem')
  const intermediatePem = readFixture('intermediate.pem')
  const foreignLeafPem = readFixture('foreign-leaf.pem')

  it('splits a multi-cert PEM bundle into every certificate', () => {
    expect(splitPemBundle(caChainPem)).toHaveLength(2)
    expect(splitPemBundle(rootPem)).toHaveLength(1)
    expect(splitPemBundle('')).toHaveLength(0)
  })

  it('parses the SPIFFE SAN, validity window, and validates the full chain', () => {
    const parsed = defaultParseX509(leafPem, caChainPem)
    expect(parsed.spiffeUri).toBe(spiffeIdFor('acct-A', 'host-1', DOMAIN))
    expect(parsed.chainValid).toBe(true)
    expect(parsed.notAfter).toBeGreaterThan(parsed.notBefore)
  })

  it('refuses when the intermediate is missing (root-only anchor is not a single hop)', () => {
    // Real path validation: leaf is signed by the intermediate, not the root directly.
    // A single-hop check against the first bundle cert would wrongly pass; chain walking refuses.
    expect(defaultParseX509(leafPem, rootPem).chainValid).toBe(false)
  })

  it('refuses when no trusted self-signed root terminates the path (intermediate only)', () => {
    expect(defaultParseX509(leafPem, intermediatePem).chainValid).toBe(false)
  })

  it('refuses a leaf signed by a foreign CA not in the trusted bundle', () => {
    expect(defaultParseX509(foreignLeafPem, caChainPem).chainValid).toBe(false)
  })

  it('refuses when the CA bundle is empty', () => {
    expect(defaultParseX509(leafPem, '').chainValid).toBe(false)
  })

  it('end-to-end: verifyAgentCert accepts the real enrolled leaf with the production parser', async () => {
    const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
    const parsed = defaultParseX509(leafPem, caChainPem)
    const now = parsed.notBefore + 60 // fixtures are long-lived; sample inside the validity window
    const r = await verifyAgentCert(leafPem, caChainPem, now, hosts, defaultParseX509)
    expect(r).toMatchObject({ ok: true, hostId: 'host-1', accountId: 'acct-A' })
  })

  it('end-to-end: verifyAgentCert refuses the real foreign leaf (chain_invalid) with the production parser', async () => {
    const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
    const parsed = defaultParseX509(foreignLeafPem, caChainPem)
    const now = parsed.notBefore + 60
    const r = await verifyAgentCert(foreignLeafPem, caChainPem, now, hosts, defaultParseX509)
    expect(r).toMatchObject({ ok: false, reason: 'chain_invalid' })
  })

  it('reports unparseable_cert when the leaf PEM is garbage', async () => {
    const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
    const r = await verifyAgentCert('not-a-cert', caChainPem, NOW, hosts, defaultParseX509)
    expect(r).toMatchObject({ ok: false, reason: 'unparseable_cert' })
  })
})

describe('rotation policy (T9)', () => {
  it('false when fresh, true at ~50% TTL, true after expiry', () => {
    const ttl = DEFAULT_ROTATION_PLAN.certTtlSeconds
    const issuedAt = NOW
    const notAfter = issuedAt + ttl
    expect(shouldRotate(notAfter, issuedAt + 1, DEFAULT_ROTATION_PLAN)).toBe(false)
    expect(shouldRotate(notAfter, issuedAt + ttl / 2, DEFAULT_ROTATION_PLAN)).toBe(true)
    expect(shouldRotate(notAfter, notAfter + 100, DEFAULT_ROTATION_PLAN)).toBe(true)
  })
})
