/**
 * TLS 1.3 Configuration
 * 
 * Implements FIPS-approved TLS configuration per DoD/MilSpec requirements:
 * - NIST SP 800-53: SC-8 (Transmission Confidentiality and Integrity)
 * - NIST SP 800-171: 3.13.1 (Cryptographic Protection in Transit)
 * 
 * Requirements:
 * - TLS 1.3 minimum
 * - FIPS-approved cipher suites only
 * - Perfect Forward Secrecy (PFS)
 * - Certificate pinning support
 */

import { getFIPSCipherSuites } from './crypto'
import { logger } from './logger'
import * as fs from 'fs'
import * as path from 'path'

export interface TLSConfig {
  cert: string
  key: string
  ca?: string
  minVersion: string
  maxVersion: string
  ciphers: string[]
  honorCipherOrder: boolean
  requestCert: boolean
  rejectUnauthorized: boolean
}

/**
 * Get FIPS-compliant TLS configuration
 */
export function getTLSConfig(): TLSConfig {
  const certPath = process.env.TLS_CERT_PATH || '/etc/ssl/certs/server.crt'
  const keyPath = process.env.TLS_KEY_PATH || '/etc/ssl/private/server.key'
  const caPath = process.env.TLS_CA_PATH

  // Validate certificate files exist
  if (!fs.existsSync(certPath)) {
    if (process.env.NODE_ENV === 'production') {
      throw new Error(`TLS certificate not found: ${certPath}`)
    }
    logger.warn(`TLS certificate not found: ${certPath} - using HTTP only`)
  }

  if (!fs.existsSync(keyPath)) {
    if (process.env.NODE_ENV === 'production') {
      throw new Error(`TLS key not found: ${keyPath}`)
    }
    logger.warn(`TLS key not found: ${keyPath} - using HTTP only`)
  }

  // Get FIPS-approved cipher suites
  const ciphers = getFIPSCipherSuites().join(':')

  return {
    cert: fs.existsSync(certPath) ? fs.readFileSync(certPath, 'utf8') : '',
    key: fs.existsSync(keyPath) ? fs.readFileSync(keyPath, 'utf8') : '',
    ca: caPath && fs.existsSync(caPath) ? fs.readFileSync(caPath, 'utf8') : undefined,
    minVersion: 'TLSv1.3', // TLS 1.3 minimum
    maxVersion: 'TLSv1.3', // Only TLS 1.3
    ciphers,
    honorCipherOrder: true, // Prefer server cipher order
    requestCert: false, // Client certificates optional (can enable for mTLS)
    rejectUnauthorized: true, // Reject unauthorized certificates
  }
}

/**
 * Get TLS options for Fastify HTTPS
 */
export function getFastifyTLSOptions(): { https: TLSConfig } | {} {
  const tlsConfig = getTLSConfig()

  if (!tlsConfig.cert || !tlsConfig.key) {
    logger.warn('TLS certificates not available - server will run on HTTP only')
    return {}
  }

  return {
    https: {
      cert: tlsConfig.cert,
      key: tlsConfig.key,
      ca: tlsConfig.ca,
      minVersion: tlsConfig.minVersion,
      maxVersion: tlsConfig.maxVersion,
      ciphers: tlsConfig.ciphers,
      honorCipherOrder: tlsConfig.honorCipherOrder,
      requestCert: tlsConfig.requestCert,
      rejectUnauthorized: tlsConfig.rejectUnauthorized,
    },
  }
}

