import { describe, expect, it } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { AgentConfig } from '../src/config/agentConfig.js'
import {
  loadHostRecord,
  resolveHostIdentity,
  saveHostRecord,
  subdomainFromCertPem,
} from '../src/config/hostRecord.js'

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

function tmpState(): string {
  return mkdtempSync(join(tmpdir(), 'wta-hr-'))
}

/** A real frp-client leaf as issued by the control-plane (SPIFFE URI SAN carries the subdomain). */
const LEAF_PEM = `-----BEGIN CERTIFICATE-----
MIIB1TCCAXygAwIBAgIUUj+CZ+6p29yI59VpyrekwSp9tAgwCgYIKoZIzj0EAwIw
EDEOMAwGA1UEAwwFaDdmZDgwHhcNMjYwNzI5MDgzNzIyWhcNMzYwNzI2MDgzNzIy
WjAQMQ4wDAYDVQQDDAVoN2ZkODBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABACg
xWQCQuxawnkkPZIgagEFtG0oBiuron4SSw3U1Q0FwCSH3BJep1MJtIuEQU3HfM4N
6Tk5kW4MWuIM8sNriiqjgbMwgbAwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMC
B4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwXAYDVR0RBFUwU4IaaDdmZDgudGVybWlu
YWwuZXhhbXBsZS5jb22GNXNwaWZmZTovL3JlbGF5LmV4YW1wbGUuY29tL2FjY291
bnQvYWNjLTEyMy9ob3N0L2g3ZmQ4MB0GA1UdDgQWBBSy/SJwjH/lm8TaY5Yk/TF+
wpg78TAKBggqhkjOPQQDAgNHADBEAiAjq1o5xpk+iF55uVfdyLP/a9OC09O0mN4P
YRk8x5MFaQIgYC3GTWqkwu0azrdffKl6jX0stbG+oM+0Cx2Cn7wy27c=
-----END CERTIFICATE-----`

describe('host record persistence', () => {
  it('round-trips the enrolment identifiers through stateDir', () => {
    const dir = tmpState()
    saveHostRecord(dir, { hostId: 'h-1', subdomain: 'h7fd8' })
    expect(loadHostRecord(dir)).toEqual({ hostId: 'h-1', subdomain: 'h7fd8' })
    rmSync(dir, { recursive: true, force: true })
  })

  it('returns null when nothing was ever enrolled here', () => {
    const dir = tmpState()
    expect(loadHostRecord(dir)).toBeNull()
    rmSync(dir, { recursive: true, force: true })
  })

  it('treats a corrupt record as absent rather than throwing (never crashes the run loop)', () => {
    const dir = tmpState()
    writeFileSync(join(dir, 'host.json'), '{not json')
    expect(loadHostRecord(dir)).toBeNull()
    rmSync(dir, { recursive: true, force: true })
  })

  it('ignores a record whose fields are the wrong shape', () => {
    const dir = tmpState()
    writeFileSync(join(dir, 'host.json'), JSON.stringify({ hostId: 42, subdomain: [] }))
    expect(loadHostRecord(dir)).toEqual({ hostId: null, subdomain: null })
    rmSync(dir, { recursive: true, force: true })
  })
})

describe('subdomainFromCertPem', () => {
  it('reads the subdomain out of the leaf SPIFFE URI SAN', () => {
    expect(subdomainFromCertPem(LEAF_PEM)).toBe('h7fd8')
  })

  it('returns null for a certificate with no SPIFFE SAN', () => {
    expect(subdomainFromCertPem('-----BEGIN CERTIFICATE-----\nnope\n-----END CERTIFICATE-----')).toBeNull()
  })

  it('returns null for garbage instead of throwing', () => {
    expect(subdomainFromCertPem('not a cert')).toBeNull()
  })
})

describe('resolveHostIdentity precedence', () => {
  it('keeps explicit config (env/argv) over everything else', () => {
    const dir = tmpState()
    saveHostRecord(dir, { hostId: 'from-file', subdomain: 'from-file' })
    const out = resolveHostIdentity(
      { ...CFG, stateDir: dir, subdomain: 'from-env', hostId: 'from-env' },
      () => LEAF_PEM,
    )
    expect(out).toEqual({ hostId: 'from-env', subdomain: 'from-env' })
    rmSync(dir, { recursive: true, force: true })
  })

  it('falls back to the persisted enrolment record', () => {
    const dir = tmpState()
    saveHostRecord(dir, { hostId: 'h-1', subdomain: 'h7fd8' })
    expect(resolveHostIdentity({ ...CFG, stateDir: dir }, () => null)).toEqual({
      hostId: 'h-1',
      subdomain: 'h7fd8',
    })
    rmSync(dir, { recursive: true, force: true })
  })

  /**
   * Hosts enrolled before the record existed have no `host.json`. Their leaf still carries the
   * subdomain, so they get an identifier in the logs without needing a re-pair.
   */
  it('falls back to the leaf SPIFFE SAN when there is no record (legacy installs)', () => {
    const dir = tmpState()
    expect(resolveHostIdentity({ ...CFG, stateDir: dir }, () => LEAF_PEM)).toEqual({
      hostId: null,
      subdomain: 'h7fd8',
    })
    rmSync(dir, { recursive: true, force: true })
  })

  it('yields nulls when nothing is known (unenrolled host)', () => {
    const dir = tmpState()
    expect(resolveHostIdentity({ ...CFG, stateDir: dir }, () => null)).toEqual({
      hostId: null,
      subdomain: null,
    })
    rmSync(dir, { recursive: true, force: true })
  })
})
