//! Identity CRUD operations.

use crate::zeroid::{
    client::{parse_api_error, ZeroIDClient},
    error::ZeroIDError,
    types::{CreateIdentityRequest, Identity, IdentityList, UpdateIdentityRequest},
};

/// Identity resource — CRUD operations on `/api/v1/identities`.
pub struct IdentitiesResource<'a> {
    pub(crate) client: &'a ZeroIDClient,
}

impl<'a> IdentitiesResource<'a> {
    /// Register a new identity.
    ///
    /// `POST /api/v1/identities`
    pub async fn create(&self, request: &CreateIdentityRequest) -> Result<Identity, 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/identities",
                headers,
                Some(&body),
            )
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// Get an identity by ID.
    ///
    /// `GET /api/v1/identities/{id}`
    pub async fn get(&self, id: &str) -> Result<Identity, ZeroIDError> {
        let path = format!("/api/v1/identities/{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 all identities for the current tenant.
    ///
    /// `GET /api/v1/identities`
    pub async fn list(&self) -> Result<IdentityList, ZeroIDError> {
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::GET, "/api/v1/identities", headers, None)
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// Update mutable fields of an identity.
    ///
    /// `PATCH /api/v1/identities/{id}`
    pub async fn update(
        &self,
        id: &str,
        request: &UpdateIdentityRequest,
    ) -> Result<Identity, ZeroIDError> {
        let path = format!("/api/v1/identities/{id}");
        let body = serde_json::to_value(request)?;
        let headers = self.client.admin_headers();
        let resp = self
            .client
            .send_with_retry(reqwest::Method::PATCH, &path, headers, Some(&body))
            .await?;
        if !resp.status().is_success() {
            return Err(parse_api_error(resp).await);
        }
        Ok(resp.json().await?)
    }

    /// Deactivate an identity (soft delete).
    ///
    /// `DELETE /api/v1/identities/{id}`
    pub async fn delete(&self, id: &str) -> Result<(), ZeroIDError> {
        let path = format!("/api/v1/identities/{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(())
    }
}
