import { readFileSync } from 'fs';
import { X509Certificate, createPrivateKey } from 'crypto';
import type { ServerTlsConfig } from '../server/config.js';
import { ensureSelfSignedCert } from './self-signed.js';

export interface ResolvedTlsOptions {
  cert: string;
  key: string;
  minVersion: 'TLSv1.2' | 'TLSv1.3';
}

/**
 * Resolve TLS material. Any failure on an operator-provided cert is FATAL
 * (throws) — never silently fall back to self-signed or HTTP, which would
 * downgrade an operator who deliberately configured a real certificate.
 */
export function resolveTlsOptions(tls: ServerTlsConfig): ResolvedTlsOptions {
  if (tls.certFile && tls.keyFile) {
    const cert = readFileSync(tls.certFile, 'utf-8');
    const key = readFileSync(tls.keyFile, 'utf-8');
    const x509 = new X509Certificate(cert);
    const priv = createPrivateKey(key);
    if (!x509.checkPrivateKey(priv)) {
      throw new Error('server.tls: cert_file and key_file do not match');
    }
    return { cert, key, minVersion: tls.minVersion };
  }
  const { cert, key } = ensureSelfSignedCert(tls.selfSignedDir, tls.selfSignedHosts);
  return { cert, key, minVersion: tls.minVersion };
}
