/**
 * T9 · Rotation policy for short-TTL agent certs (INV14). Certs are short-lived (e.g. 1h) and
 * renewed at ~50% of TTL, so revocation = "stop renewing + kill tunnel" (T10) — no CRL/OCSP.
 * Rotation mid-tunnel is seamless: a new valid cert supersedes without dropping the stream.
 */
export interface RotationPlan {
  readonly renewAtSeconds: number // lead time after issue to begin renewing (≈ 50% of certTtlSeconds)
  readonly certTtlSeconds: number // total cert lifetime (short)
}

export const DEFAULT_CERT_TTL_SECONDS = 3600 as const

/** Default plan: 1h TTL, renew at 50%. */
export const DEFAULT_ROTATION_PLAN: RotationPlan = {
  renewAtSeconds: DEFAULT_CERT_TTL_SECONDS / 2,
  certTtlSeconds: DEFAULT_CERT_TTL_SECONDS,
}

/**
 * true when `now` has reached the renew threshold (issuedAt + renewAtSeconds) OR the cert has
 * expired; false when the cert is still fresh. `certNotAfter`/`now` are epoch seconds.
 */
export function shouldRotate(certNotAfter: number, now: number, plan: RotationPlan): boolean {
  const issuedAt = certNotAfter - plan.certTtlSeconds
  const renewThreshold = issuedAt + plan.renewAtSeconds
  return now >= renewThreshold
}
