use std::sync::Arc;

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

use crate::dagger_middleware::DaggerMiddleware;

use super::RustService;

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

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

#[async_trait]
impl DaggerMiddleware for CuddleCli {
    async fn handle(&self, container: Container) -> eyre::Result<Container> {
        let cuddle = self
            .client
            .container()
            .from("kasperhermansen/cuddle:latest");

        Ok(container.with_file(
            "/usr/local/bin/cuddle",
            cuddle.file("/usr/local/cargo/bin/cuddle"),
        ))
    }
}

pub trait CuddleCliExt {
    fn with_cuddle_cli(&mut self) -> &mut Self {
        self
    }
}

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

        self
    }
}
