import { describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { AgentConfig } from '../src/config/agentConfig.js'
import { generateIdentity } from '../src/keys/identity.js'
import { openKeystore } from '../src/keys/keystore.js'
import {
  computeRenewDelayMs,
  createCertRotator,
  renewCert,
  renewalUrlFor,
} from '../src/certs/rotation.js'
import { FakeTimer } from './fixtures/fakes.js'

const CFG: AgentConfig = {
  relayUrl: 'wss://relay/agent',
  enrollUrl: 'https://example.com/enroll',
  stateDir: '/tmp/x',
  localTargetUrl: 'ws://127.0.0.1:3000',
  subdomain: 'host-42',
  hostId: 'h-1',
}

function enrolledKs() {
  const dir = mkdtempSync(join(tmpdir(), 'wta-rot-'))
  const ks = openKeystore(dir)
  ks.saveIdentity(generateIdentity())
  ks.saveCert('OLDCERT', 'OLDCA')
  return { dir, ks }
}

function jsonRes(status: number, body: unknown): Response {
  return { ok: status >= 200 && status < 300, status, json: async () => body } as unknown as Response
}

describe('cert rotation math (T13)', () => {
  it('derives P3 renewal URL from enrollUrl', () => {
    expect(renewalUrlFor(CFG)).toBe('https://example.com/renew')
  })

  it('renews renewBeforeMs before expiry, clamped at 0', () => {
    const now = new Date('2026-01-01T00:00:00Z')
    const parse = () => new Date('2026-01-01T01:00:00Z') // expires in 1h
    expect(computeRenewDelayMs('C', 5 * 60_000, now, parse)).toBe(55 * 60_000)
    const parsePast = () => new Date('2025-01-01T00:00:00Z')
    expect(computeRenewDelayMs('C', 5 * 60_000, now, parsePast)).toBe(0)
  })
})

describe('renewCert (T13)', () => {
  it('installs a fresh cert atomically on success (same key)', async () => {
    const { dir, ks } = enrolledKs()
    const before = ks.loadIdentity()!.publicKey
    const fetchImpl = vi.fn(async () => jsonRes(200, { cert: 'NEWCERT', caChain: 'NEWCA' }))
    const out = await renewCert(CFG, ks.loadIdentity()!, ks, fetchImpl as unknown as typeof fetch)
    expect(out).toBe('rotated')
    expect(ks.loadCert()).toEqual({ certPem: 'NEWCERT', caChainPem: 'NEWCA' })
    // pubkey unchanged — only the cert rotated
    expect(Buffer.from(ks.loadIdentity()!.publicKey).equals(Buffer.from(before))).toBe(true)
    rmSync(dir, { recursive: true, force: true })
  })

  it('403 → revoked (⇒ T14 teardown, INV12)', async () => {
    const { dir, ks } = enrolledKs()
    const fetchImpl = async () => jsonRes(403, {})
    const out = await renewCert(CFG, ks.loadIdentity()!, ks, fetchImpl as unknown as typeof fetch)
    expect(out).toBe('revoked')
    expect(ks.loadCert()).toEqual({ certPem: 'OLDCERT', caChainPem: 'OLDCA' }) // untouched
    rmSync(dir, { recursive: true, force: true })
  })
})

const flush = () => new Promise((r) => setImmediate(r))

describe('createCertRotator (T13)', () => {
  it('fires onRevoked when the scheduled renewal returns 403', async () => {
    const { dir, ks } = enrolledKs()
    const timer = new FakeTimer()
    const rotator = createCertRotator(CFG, ks.loadIdentity()!, ks, {
      timer,
      renewBeforeMs: 1000,
      fetchImpl: (async () => jsonRes(403, {})) as unknown as typeof fetch,
      now: () => new Date(0),
      parseCert: () => new Date(2000), // expires 2s after epoch → delay ~1000ms
    })
    let revoked = false
    rotator.onRevoked(() => {
      revoked = true
    })
    rotator.start()
    timer.advance(1000) // scheduled renewal fires
    await flush()
    expect(revoked).toBe(true)
    rmSync(dir, { recursive: true, force: true })
  })

  it('rotates and reschedules on a successful renewal (seamless)', async () => {
    const { dir, ks } = enrolledKs()
    const timer = new FakeTimer()
    const rotator = createCertRotator(CFG, ks.loadIdentity()!, ks, {
      timer,
      renewBeforeMs: 1000,
      fetchImpl: (async () => jsonRes(200, { cert: 'NEWCERT', caChain: 'NEWCA' })) as unknown as typeof fetch,
      now: () => new Date(0),
      parseCert: () => new Date(2000),
    })
    let rotated = 0
    rotator.onRotated(() => {
      rotated += 1
    })
    rotator.start()
    timer.advance(1000)
    await flush()
    expect(rotated).toBe(1)
    expect(ks.loadCert()!.certPem).toBe('NEWCERT')
    rotator.stop()
    rmSync(dir, { recursive: true, force: true })
  })
})
