use anyhow::{bail, Context, Result};
use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use std::fs::File;
use std::io::BufReader;
use tokio_rustls::TlsAcceptor;

/// Create a TLS acceptor from certificate and key files
/// This function is shared between TCP SSL and WSS implementations
pub async fn create_tls_acceptor(
    cert_file: &std::path::Path,
    key_file: &std::path::Path,
) -> Result<TlsAcceptor> {
    // Load certificates from PEM file
    let cert_file = File::open(cert_file).context("Failed to open SSL certificate file")?;
    let mut cert_reader = BufReader::new(cert_file);
    let certs: Vec<CertificateDer> = CertificateDer::pem_reader_iter(&mut cert_reader)
        .collect::<Result<Vec<_>, _>>()
        .context("Failed to read certificate file")?;

    if certs.is_empty() {
        bail!("No certificates found in certificate file");
    }

    // Load private key from PEM file
    let key_file = File::open(key_file).context("Failed to open SSL private key file")?;
    let mut key_reader = BufReader::new(key_file);
    let key = PrivateKeyDer::from_pem_reader(&mut key_reader)
        .context("Failed to read private key file")?;

    // Create the TLS server configuration
    let config = rustls::ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs, key)
        .context("Failed to create TLS server config")?;

    Ok(TlsAcceptor::from(std::sync::Arc::new(config)))
}
