import { describe, expect, it } from 'vitest'
import { X509Certificate } from 'node:crypto'
import { generateIdentity } from '../src/keys/identity.js'
import { buildCsr } from '../src/enroll/csr.js'

describe('PKCS#10 CSR (T4)', () => {
  it('emits a PEM CERTIFICATE REQUEST', () => {
    const csr = buildCsr(generateIdentity(), 'host-42.term.example.com')
    expect(csr).toContain('-----BEGIN CERTIFICATE REQUEST-----')
    expect(csr).toContain('-----END CERTIFICATE REQUEST-----')
  })

  it('does not contain private-key material (INV4)', () => {
    const id = generateIdentity()
    const csr = buildCsr(id, 'host-42')
    expect(csr).not.toContain('PRIVATE KEY')
    expect(csr).not.toContain(id.exportPrivatePkcs8Pem().split('\n')[1]!)
  })

  it('produces a syntactically decodable DER structure', () => {
    // Node can't parse a CSR directly, but the base64 body must be valid DER (a SEQUENCE).
    const csr = buildCsr(generateIdentity(), 'host-42')
    const b64 = csr
      .replace(/-----[A-Z ]+-----/g, '')
      .replace(/\s+/g, '')
    const der = Buffer.from(b64, 'base64')
    expect(der[0]).toBe(0x30) // outer SEQUENCE tag
    expect(der.length).toBeGreaterThan(64)
    // sanity: X509Certificate exists (crypto available) — unrelated smoke to keep import used
    expect(typeof X509Certificate).toBe('function')
  })
})
