use anyhow::Result;

use crate::api::PlaneApiClient;
use crate::config::{ProjectScope, resolve_plane_session};

/// Shows current user info, active workspace, and default project configuration.
/// Confirms authentication works by fetching the current user's member UUID
/// from the Plane API, then displays the resolved session targeting.
/// Usage: `plane whoami`
#[derive(clap::Args)]
pub struct WhoamiArgs;

/// Execution logic for the `plane whoami` subcommand
impl WhoamiArgs {
    /// Resolves the active session, fetches the authenticated user's member UUID,
    /// and prints the session targeting summary
    pub async fn execute(self) -> Result<()> {
        let plane_session = resolve_plane_session()?;
        let workspace_display = plane_session.workspace_slug().to_string();
        let project_display = match plane_session.project_scope() {
            ProjectScope::Scoped(project_slug) => project_slug.to_string(),
            ProjectScope::ExplicitOnly => String::from("none (use --project)"),
        };

        let api_client = PlaneApiClient::try_new(plane_session)?;
        let member_id = api_client.current_user_member_id().await?;

        let config_path = resolve_config_display_path();

        println!("User:      {}", member_id);
        println!("Workspace: {}", workspace_display);
        println!("Project:   {}", project_display);
        println!("Config:    {}", config_path);

        Ok(())
    }
}

/// Builds the display path for the config file, falling back to a placeholder
/// when the home directory cannot be determined
fn resolve_config_display_path() -> String {
    match dirs::home_dir() {
        Option::Some(home_directory) => {
            home_directory
                .join(".plane-cli-requiem")
                .join("config.toml")
                .display()
                .to_string()
        }
        Option::None => String::from("~/.plane-cli-requiem/config.toml"),
    }
}
