//! OAuth 2.0 token issuance methods for `AgentIdPClient`.
//!
//! Covers `POST /oauth2/token` for issuing agent-scoped access tokens.

use crate::agents::parse_response;
use crate::client::AgentIdPClient;
use crate::error::AgentIdPError;
use crate::models::TokenResponse;

impl AgentIdPClient {
    /// Issues an OAuth 2.0 access token for the given agent with the requested scopes.
    ///
    /// `POST /oauth2/token` (form body) → `200 TokenResponse`
    ///
    /// This differs from the internal `TokenManager` token fetch in that it
    /// allows callers to request tokens for specific agent IDs and scope sets.
    ///
    /// # Arguments
    ///
    /// * `agent_id` — The agent on whose behalf the token is issued.
    /// * `scopes` — Scopes to request (e.g. `&["agents:read", "agents:write"]`).
    pub async fn issue_token(
        &self,
        agent_id: &str,
        scopes: &[&str],
    ) -> Result<TokenResponse, AgentIdPError> {
        let auth = self.get_auth_header().await?;
        let url = format!("{}/oauth2/token", self.base_url);
        let scope_str = scopes.join(" ");

        let params = [
            ("grant_type", "client_credentials"),
            ("agent_id", agent_id),
            ("scope", scope_str.as_str()),
        ];

        let resp = self
            .http
            .post(&url)
            .header("Authorization", auth)
            .form(&params)
            .send()
            .await?;

        parse_response(resp).await
    }
}
