use std::sync::Arc;

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

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

use super::RustService;

pub struct RustWorkspace {}

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

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

#[async_trait]
impl DaggerMiddleware for RustWorkspace {
    async fn handle(&self, container: Container) -> eyre::Result<Container> {
        Ok(container)
    }
}

#[async_trait]
pub trait RustWorkspaceExt {
    async fn with_workspace_crates(&mut self) -> &mut Self {
        self
    }
}

#[async_trait]
impl RustWorkspaceExt for RustService {
    async fn with_workspace_crates(&mut self) -> &mut Self {
        self.with_crates(get_members().await)
            .with_stage(super::RustServiceStage::BeforeDeps(Arc::new(
                RustWorkspace::new(),
            )))
    }
}

#[async_trait]
impl RustWorkspaceExt for LeptosService {
    async fn with_workspace_crates(&mut self) -> &mut Self {
        self.with_crates(get_members().await)
            .with_stage(super::RustServiceStage::BeforeDeps(Arc::new(
                RustWorkspace::new(),
            )))
    }
}

async fn get_members() -> Vec<String> {
    if let Ok(Some(file)) = rust_workspace::File::read_file().await {
        if let Some(members) = file.get_workspace_members() {
            return members;
        }
    }

    Vec::new()
}
