use anyhow::Result;

use crate::config::{
    load_plane_settings, save_plane_settings, DefaultTarget, PlaneSettings, WorkspaceRegistry,
    WorkspaceSlug,
};

/// Switches the active workspace that all subsequent commands target.
/// The selected workspace must already be registered via `plane config`.
/// Project scope is read from the workspace's own entry, not a global setting.
#[derive(clap::Args)]
pub struct SwitchWorkspaceArgs {
    /// Slug of the workspace to switch to (must already be registered)
    workspace_slug: String,
}

/// Execution logic for the `plane workspace` subcommand
impl SwitchWorkspaceArgs {
    /// Validates the target workspace exists in the registry, updates the active workspace
    /// in the persisted settings file, and confirms the switch to the user
    pub async fn execute(self) -> Result<()> {
        let validated_slug: WorkspaceSlug = self.workspace_slug.parse()?;

        let current_plane_settings = load_plane_settings()?;
        let (_current_target, current_registry) = current_plane_settings.into_parts();

        if current_registry.get(&validated_slug).is_none() {
            anyhow::bail!(
                "workspace '{}' is not registered — run: plane config --workspace {} --token <api-key>",
                validated_slug,
                validated_slug
            );
        }

        let new_target = DefaultTarget::WorkspaceOnly(validated_slug);

        let updated_settings = PlaneSettings::with_target(new_target)
            .with_workspaces(current_registry);

        save_plane_settings(&updated_settings)?;
        println!(
            "switched to workspace '{}'",
            self.workspace_slug
        );

        Ok(())
    }
}
