//! Public marketplace methods for `AgentIdPClient`.
//!
//! Covers `GET /marketplace/agents` and `GET /marketplace/agents/{id}`.
//! These endpoints are **unauthenticated** — no `Authorization` header is sent.

use crate::agents::parse_response;
use crate::client::AgentIdPClient;
use crate::error::AgentIdPError;
use crate::models::{MarketplaceAgent, MarketplaceAgentList, MarketplaceFilters};

impl AgentIdPClient {
    /// Lists publicly available agents in the marketplace.
    ///
    /// `GET /marketplace/agents` → `200 MarketplaceAgentList`
    ///
    /// This endpoint does **not** require authentication. `None` filter fields
    /// are omitted from the query string.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use sentryagent_idp::{AgentIdPClient, MarketplaceFilters};
    ///
    /// # async fn example(client: &AgentIdPClient) -> Result<(), sentryagent_idp::AgentIdPError> {
    /// let results = client.list_public_agents(MarketplaceFilters {
    ///     q: Some("summarizer".to_owned()),
    ///     capability: None,
    ///     publisher: None,
    ///     page: 1,
    ///     per_page: 20,
    /// }).await?;
    /// println!("Found {} agents", results.total);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_public_agents(
        &self,
        filters: MarketplaceFilters,
    ) -> Result<MarketplaceAgentList, AgentIdPError> {
        let url = format!("{}/marketplace/agents", self.base_url);

        let mut query: Vec<(&str, String)> = vec![
            ("page", filters.page.to_string()),
            ("per_page", filters.per_page.to_string()),
        ];

        if let Some(ref q) = filters.q {
            query.push(("q", q.clone()));
        }
        if let Some(ref capability) = filters.capability {
            query.push(("capability", capability.clone()));
        }
        if let Some(ref publisher) = filters.publisher {
            query.push(("publisher", publisher.clone()));
        }

        let resp = self
            .http
            .get(&url)
            .query(&query)
            .send()
            .await?;

        parse_response(resp).await
    }

    /// Retrieves a single publicly listed marketplace agent by ID.
    ///
    /// `GET /marketplace/agents/{id}` → `200 MarketplaceAgent`
    ///
    /// This endpoint does **not** require authentication.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::AgentIdPError::NotFound`] when no public agent
    /// with the given ID exists.
    pub async fn get_public_agent(
        &self,
        agent_id: &str,
    ) -> Result<MarketplaceAgent, AgentIdPError> {
        let url = format!("{}/marketplace/agents/{}", self.base_url, agent_id);

        let resp = self.http.get(&url).send().await?;

        parse_response(resp).await
    }
}
