//! Audit log methods for `AgentIdPClient`.
//!
//! Covers `GET /audit-logs` with optional query-parameter filters.

use crate::agents::parse_response;
use crate::client::AgentIdPClient;
use crate::error::AgentIdPError;
use crate::models::{AuditLogFilters, AuditLogList};

impl AgentIdPClient {
    /// Queries the audit log with optional filters.
    ///
    /// `GET /audit-logs` → `200 AuditLogList`
    ///
    /// Only `Some` fields in `filters` are appended as query parameters.
    /// `page` and `per_page` are always included.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use sentryagent_idp::{AgentIdPClient, AuditLogFilters};
    ///
    /// # async fn example(client: &AgentIdPClient) -> Result<(), sentryagent_idp::AgentIdPError> {
    /// let logs = client.list_audit_logs(AuditLogFilters {
    ///     agent_id: Some("agent-uuid".to_owned()),
    ///     event_type: Some("token.issued".to_owned()),
    ///     from: None,
    ///     to: None,
    ///     page: 1,
    ///     per_page: 50,
    /// }).await?;
    /// println!("Total events: {}", logs.total);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_audit_logs(
        &self,
        filters: AuditLogFilters,
    ) -> Result<AuditLogList, AgentIdPError> {
        let auth = self.get_auth_header().await?;
        let url = format!("{}/audit-logs", self.base_url);

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

        if let Some(ref agent_id) = filters.agent_id {
            query.push(("agent_id", agent_id.clone()));
        }
        if let Some(ref event_type) = filters.event_type {
            query.push(("event_type", event_type.clone()));
        }
        if let Some(ref from) = filters.from {
            query.push(("from", from.clone()));
        }
        if let Some(ref to) = filters.to {
            query.push(("to", to.clone()));
        }

        let resp = self
            .http
            .get(&url)
            .header("Authorization", auth)
            .query(&query)
            .send()
            .await?;

        parse_response(resp).await
    }
}
