//! TLS 配置构建器 (rustls 0.21)

use rustls::{Certificate, PrivateKey, ServerConfig};
use rustls_pemfile::{certs, pkcs8_private_keys, rsa_private_keys};
use std::io::BufReader;
use std::sync::Arc;
use tokio_rustls::TlsAcceptor;

use super::CertificateBundle;
use crate::utils::AppError;

/// TLS 配置构建器
pub struct TlsConfigBuilder;

impl TlsConfigBuilder {
    /// 从证书包构建服务端 TLS 配置
    pub fn build_server_config(bundle: &CertificateBundle) -> Result<Arc<ServerConfig>, AppError> {
        // 解析证书
        let cert_chain = Self::parse_certificates(&bundle.cert_pem)?;
        
        // 解析私钥
        let private_key = Self::parse_private_key(&bundle.key_pem)?;

        // 构建 ServerConfig
        let config = ServerConfig::builder()
            .with_safe_defaults()
            .with_no_client_auth()
            .with_single_cert(cert_chain, private_key)
            .map_err(|e| AppError::Tls(format!("Failed to build TLS config: {}", e)))?;

        Ok(Arc::new(config))
    }

    /// 创建 TLS Acceptor (用于接受 TLS 连接)
    pub fn build_acceptor(bundle: &CertificateBundle) -> Result<TlsAcceptor, AppError> {
        let config = Self::build_server_config(bundle)?;
        Ok(TlsAcceptor::from(config))
    }

    /// 解析 PEM 格式的证书链
    fn parse_certificates(pem: &str) -> Result<Vec<Certificate>, AppError> {
        let mut reader = BufReader::new(pem.as_bytes());
        let certs_raw = certs(&mut reader)
            .map_err(|e| AppError::Tls(format!("Failed to parse certificate: {}", e)))?;

        if certs_raw.is_empty() {
            return Err(AppError::Tls("No certificates found in PEM".to_string()));
        }

        Ok(certs_raw.into_iter().map(Certificate).collect())
    }

    /// 解析 PEM 格式的私钥
    fn parse_private_key(pem: &str) -> Result<PrivateKey, AppError> {
        let mut reader = BufReader::new(pem.as_bytes());
        
        // 尝试 PKCS8 格式
        let keys = pkcs8_private_keys(&mut reader)
            .map_err(|e| AppError::Tls(format!("Failed to parse private key: {}", e)))?;
        
        if let Some(key) = keys.into_iter().next() {
            return Ok(PrivateKey(key));
        }

        // 尝试 RSA 格式
        let mut reader = BufReader::new(pem.as_bytes());
        let keys = rsa_private_keys(&mut reader)
            .map_err(|e| AppError::Tls(format!("Failed to parse RSA key: {}", e)))?;
        
        keys.into_iter()
            .next()
            .map(PrivateKey)
            .ok_or_else(|| AppError::Tls("No private key found in PEM".to_string()))
    }
}

/// 创建跳过证书验证的客户端配置 (用于自签名证书)
pub mod client {
    use rustls::client::{ServerCertVerified, ServerCertVerifier};
    use rustls::{Certificate, ClientConfig, ServerName};
    use std::sync::Arc;
    use std::time::SystemTime;
    use tokio_rustls::TlsConnector;

    use crate::utils::AppError;

    /// 跳过验证的证书验证器 (仅用于自签名证书场景)
    struct SkipServerVerification;

    impl ServerCertVerifier for SkipServerVerification {
        fn verify_server_cert(
            &self,
            _end_entity: &Certificate,
            _intermediates: &[Certificate],
            _server_name: &ServerName,
            _scts: &mut dyn Iterator<Item = &[u8]>,
            _ocsp_response: &[u8],
            _now: SystemTime,
        ) -> Result<ServerCertVerified, rustls::Error> {
            Ok(ServerCertVerified::assertion())
        }
    }

    /// 构建客户端 TLS 配置 (跳过证书验证)
    pub fn build_client_config() -> Result<Arc<ClientConfig>, AppError> {
        let config = ClientConfig::builder()
            .with_safe_defaults()
            .with_custom_certificate_verifier(Arc::new(SkipServerVerification))
            .with_no_client_auth();

        Ok(Arc::new(config))
    }

    /// 创建 TLS Connector
    pub fn build_connector() -> Result<TlsConnector, AppError> {
        let config = build_client_config()?;
        Ok(TlsConnector::from(config))
    }
}
