//! OAuth2 client management operations.

use crate::zeroid::{
    client::{parse_api_error, ZeroIDClient},
    error::ZeroIDError,
    types::{
        CreateOAuthClientRequest, OAuthClient, OAuthClientCreated, OAuthClientDeleted,
        OAuthClientList,
    },
};

/// OAuth clients resource — CRUD on `/api/v1/oauth/clients`.
pub struct OAuthClientsResource<'a> {
    pub(crate) client: &'a ZeroIDClient,
}

impl<'a> OAuthClientsResource<'a> {
    /// Register a new OAuth2 client.
    ///
    /// `POST /api/v1/oauth/clients`
    pub async fn create(
        &self,
        request: &CreateOAuthClientRequest,
    ) -> Result<OAuthClientCreated, ZeroIDError> {
        let body = serde_json::to_value(request)?;
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(
                reqwest::Method::POST,
                "/api/v1/oauth/clients",
                headers,
                Some(&body),
            )
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// Get an OAuth2 client by ID.
    ///
    /// `GET /api/v1/oauth/clients/{id}`
    pub async fn get(&self, id: &str) -> Result<OAuthClient, ZeroIDError> {
        let path = format!("/api/v1/oauth/clients/{id}");
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::GET, &path, headers, None)
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// List OAuth2 clients for the current tenant.
    ///
    /// `GET /api/v1/oauth/clients`
    pub async fn list(&self) -> Result<OAuthClientList, ZeroIDError> {
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::GET, "/api/v1/oauth/clients", headers, None)
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// Rotate an OAuth2 client secret.
    ///
    /// `POST /api/v1/oauth/clients/{id}/rotate-secret`
    pub async fn rotate_secret(&self, id: &str) -> Result<OAuthClientCreated, ZeroIDError> {
        let path = format!("/api/v1/oauth/clients/{id}/rotate-secret");
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::POST, &path, headers, None)
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// Delete an OAuth2 client.
    ///
    /// `DELETE /api/v1/oauth/clients/{id}`
    pub async fn delete(&self, id: &str) -> Result<OAuthClientDeleted, ZeroIDError> {
        let path = format!("/api/v1/oauth/clients/{id}");
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::DELETE, &path, headers, None)
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }
}
