Documentation
use std::path::PathBuf;

use faststr::FastStr;

use super::LoadCert;
use crate::{
  cert::Cert,
  error::{Error, Result},
};

#[derive(Debug)]
pub struct CertDir {
  pub base: PathBuf,
}

impl LoadCert for CertDir {
  fn load(&self, host: impl Into<FastStr>) -> Result<Option<Cert>> {
    let host = host.into();
    // 证书和私钥的路径
    let cert_path = self.base.join(format!("{host}_ecc/fullchain.cer"));
    let key_path = self.base.join(format!("{host}_ecc/{host}.key"));

    if !cert_path.exists() || !key_path.exists() {
      return Ok(None);
    }

    // 同步读取文件内容
    let cert_str = std::fs::read_to_string(cert_path).map_err(Error::Io)?;
    let key_str = std::fs::read_to_string(key_path).map_err(Error::Io)?;

    Cert::new(cert_str, key_str).map(Some)
  }
}