use crate::api::Workspace;
use crate::apis::workspaces_api;
use anyhow::Result;

pub async fn list_workspaces(token: &str) -> Result<Vec<Workspace>> {
    workspaces_api::list_workspaces(token).await
}

pub async fn create_workspace(token: &str, name: &str) -> Result<String> {
    workspaces_api::create_workspace(token, name).await
}

pub async fn resolve_workspace_id(token: &str, selector: &str) -> Result<String> {
    if selector.len() == 36 && selector.contains('-') {
        Ok(selector.to_string())
    } else {
        let workspaces = list_workspaces(token).await?;
        let workspace = workspaces
            .iter()
            .find(|w| w.slug == selector)
            .ok_or_else(|| anyhow::anyhow!("Workspace '{}' not found", selector))?;
        Ok(workspace.id.clone())
    }
}

pub async fn get_workspace(token: &str, workspace_id: &str) -> Result<Workspace> {
    let workspaces = list_workspaces(token).await?;
    workspaces
        .into_iter()
        .find(|w| w.id == workspace_id)
        .ok_or_else(|| anyhow::anyhow!("Workspace not found"))
}

pub async fn update_workspace(token: &str, workspace_id: &str, name: &str) -> Result<()> {
    workspaces_api::update_workspace(token, workspace_id, name).await
}

pub async fn delete_workspace(token: &str, workspace_id: &str) -> Result<()> {
    workspaces_api::delete_workspace(token, workspace_id).await
}
