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 Apt {
    deps: Vec<String>,
}

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

impl Apt {
    pub fn new() -> Self {
        Self { deps: Vec::new() }
    }

    pub fn add(mut self, dep_name: impl Into<String>) -> Self {
        self.deps.push(dep_name.into());

        self
    }

    pub fn extend(mut self, deps: &[&str]) -> Self {
        self.deps.extend(deps.iter().map(|s| s.to_string()));

        self
    }
}

#[async_trait]
impl DaggerMiddleware for Apt {
    async fn handle(&self, container: Container) -> eyre::Result<Container> {
        let mut deps = vec!["apt", "install", "-y"];
        deps.extend(self.deps.iter().map(|s| s.as_str()));

        let c = container.with_exec(vec!["apt", "update"]).with_exec(deps);

        Ok(c)
    }
}

pub trait AptExt {
    fn with_apt(&mut self, deps: &[&str]) -> &mut Self {
        self
    }

    fn with_apt_release(&mut self, deps: &[&str]) -> &mut Self {
        self
    }
}

impl AptExt for RustService {
    fn with_apt(&mut self, deps: &[&str]) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforeDeps(Arc::new(
            Apt::new().extend(deps),
        )))
    }

    fn with_apt_release(&mut self, deps: &[&str]) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforePackage(Arc::new(
            Apt::new().extend(deps),
        )))
    }
}

impl AptExt for LeptosService {
    fn with_apt(&mut self, deps: &[&str]) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforeDeps(Arc::new(
            Apt::new().extend(deps),
        )))
    }

    fn with_apt_release(&mut self, deps: &[&str]) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforePackage(Arc::new(
            Apt::new().extend(deps),
        )))
    }
}
