use anyhow::Result;

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

/// Posts a comment on a work item from the command line.
/// Usage: `plane comment NRO-123 "This is done"`
#[derive(clap::Args)]
pub struct PostCommentArgs {
    /// Work item identifier (e.g. "NRO-123")
    identifier: String,
    /// Comment text to post
    comment_text: String,
}

/// Execution logic for the `plane comment` subcommand
impl PostCommentArgs {
    /// Resolves the work item, posts the comment via the API, and confirms
    pub async fn execute(self) -> Result<()> {
        let plane_session = resolve_plane_session()?;
        let api_client = PlaneApiClient::try_new(plane_session)?;

        let work_item_identifier: WorkItemIdentifier = self.identifier.parse()?;
        let fetched_work_item = api_client
            .find_work_item_by_identifier(&work_item_identifier)
            .await?;

        let project_client = api_client.project_operations(fetched_work_item.project_id());
        let item_client = project_client.work_item_operations(fetched_work_item.id());
        item_client.post_comment(&self.comment_text).await?;

        println!("Commented on {}", work_item_identifier);
        Ok(())
    }
}
