use std::sync::Arc;

use async_trait::async_trait;
use dagger_sdk::{Container};

use crate::dagger_middleware::DaggerMiddleware;

use super::RustService;

pub struct DockerCli {
    client: dagger_sdk::Query,
}

impl DockerCli {
    pub fn new(client: dagger_sdk::Query) -> Self {
        Self { client }
    }
}

#[async_trait]
impl DaggerMiddleware for DockerCli {
    async fn handle(&self, container: Container) -> eyre::Result<Container> {
        let docker = self.client.container().from("docker:cli");

        Ok(container
            .with_file(
                "/usr/local/bin/docker",
                docker.file("/usr/local/bin/docker"),
            )
            .with_directory("/certs", docker.directory("/certs")))
    }
}

pub trait DockerCliExt {
    fn with_docker_cli(&mut self) -> &mut Self {
        self
    }
}

impl DockerCliExt for RustService {
    fn with_docker_cli(&mut self) -> &mut Self {
        self.with_stage(super::RustServiceStage::BeforePackage(Arc::new(
            DockerCli::new(self.client.clone()),
        )));

        self
    }
}
