//! `ph search <query>`: Search products and makers.

use ph_cli_core::{Client, Result, SearchResult};

/// Execute the search command.
pub async fn execute(
    client: &mut Client,
    query: &str,
    limit: Option<usize>,
    as_json: bool,
) -> Result<()> {
    let results = client.search(query, limit).await?;

    if results.is_empty() {
        if as_json {
            println!("[]");
        } else {
            println!("No results found for '{}'.", query);
        }
        return Ok(());
    }

    if as_json {
        let json = serde_json::to_string_pretty(&results)?;
        println!("{}", json);
    } else {
        print_results(query, &results);
    }

    Ok(())
}

/// Pretty-print search results.
fn print_results(query: &str, results: &[SearchResult]) {
    println!("\n  Search results for '{}':\n", query);

    for (i, result) in results.iter().enumerate() {
        let (icon, _kind) = match result {
            SearchResult::Post(_) => ("🔶", "Product"),
            SearchResult::User(_) => ("👤", "Maker"),
        };

        println!(
            "  {} {:<3} {} - {}",
            icon,
            i + 1,
            result.label(),
            result.sub_label(),
        );

        if let SearchResult::Post(post) = result {
            println!(
                "      {} votes · {} comments · {}",
                post.votes_count,
                post.comments_count,
                post.topics
                    .iter()
                    .map(|t| t.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", "),
            );
        }
    }

    println!("\n  Total: {} results", results.len());
    println!("  Tip: Run `ph post <id>` for details.\n");
}
