use std::sync::Arc;

use async_trait::async_trait;
use dagger_sdk::Container;

use crate::{dagger_middleware::DaggerMiddleware, leptos_service::LeptosService};

use super::RustService;

pub struct AptCaCertificates {}

impl Default for AptCaCertificates {
    fn default() -> Self {
        Self::new()
    }
}

impl AptCaCertificates {
    pub fn new() -> Self {
        Self {}
    }
}

#[async_trait]
impl DaggerMiddleware for AptCaCertificates {
    async fn handle(&self, container: Container) -> eyre::Result<Container> {
        let c = container
            .with_exec(vec!["apt", "update"])
            .with_exec(vec!["apt", "install", "-y", "ca-certificates"])
            .with_exec(vec!["update-ca-certificates"]);

        Ok(c)
    }
}

pub trait AptCaCertificatesExt {
    fn with_apt_ca_certificates(&mut self) -> &mut Self {
        self
    }
}

impl AptCaCertificatesExt for RustService {
    fn with_apt_ca_certificates(&mut self) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforeDeps(Arc::new(
            AptCaCertificates::new(),
        )))
        .with_stage(super::RustServiceStage::BeforePackage(Arc::new(
            AptCaCertificates::new(),
        )))
    }
}

impl AptCaCertificatesExt for LeptosService {
    fn with_apt_ca_certificates(&mut self) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforeDeps(Arc::new(
            AptCaCertificates::new(),
        )))
        .with_stage(super::RustServiceStage::BeforePackage(Arc::new(
            AptCaCertificates::new(),
        )))
    }
}
