/*
 * Artifact Keeper API
 *
 * Enterprise artifact registry supporting 45+ package formats.  ## Authentication  The JSON management API under `/api/v1/_*` accepts **API tokens only as `Authorization: Bearer <token>`**. This is the canonical scheme for programmatic access; JWTs issued by the login flow also use `Bearer`. HTTP Basic credentials on `/api/v1/_*` are validated *only* as a real `username:password` login — the password half is **not** retried as an API token. A request to `/api/v1/_*` that sends an API token in the password field of Basic auth therefore returns `401 AUTH_ERROR`; switch to `Authorization: Bearer <token>`.  Format (package-manager) endpoints such as `/v2/_*` (OCI), `/incus/_*`, `/debian/_*`, and the language registries are intentionally more permissive for client compatibility: in addition to Bearer, they accept HTTP **Basic** auth with the API token supplied in the *password* field (any username), matching the `pip` netrc / Artifactory-style `token:<api_token>` convention used by package managers that cannot send a Bearer header. This Basic-with-token fallback applies to format endpoints only, never to `/api/v1/_*`.
 *
 * The version of the OpenAPI document: 1.3.0
 * 
 * Generated by: https://openapi-generator.tech
 */


use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration, ContentType};


/// struct for typed errors of method [`health_check`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HealthCheckError {
    Status503(models::HealthResponse),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`liveness_check`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LivenessCheckError {
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`metrics`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MetricsError {
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`readiness_check`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ReadinessCheckError {
    Status503(models::ReadyzResponse),
    UnknownValue(serde_json::Value),
}


/// Checks database, storage (real write/read probe), optional services (Trivy, OpenSearch), and exposes DB connection pool statistics.
pub async fn health_check(configuration: &configuration::Configuration, ) -> Result<models::HealthResponse, Error<HealthCheckError>> {

    let uri_str = format!("{}/health", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::HealthResponse`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::HealthResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<HealthCheckError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Takes no State parameter. If Axum can route the request and execute this function, the process is alive. External service failures cannot trigger pod restarts.
pub async fn liveness_check(configuration: &configuration::Configuration, ) -> Result<models::LivezResponse, Error<LivenessCheckError>> {

    let uri_str = format!("{}/livez", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::LivezResponse`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::LivezResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<LivenessCheckError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

pub async fn metrics(configuration: &configuration::Configuration, ) -> Result<(), Error<MetricsError>> {

    let uri_str = format!("{}/api/v1/admin/metrics", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();

    if !status.is_client_error() && !status.is_server_error() {
        Ok(())
    } else {
        let content = resp.text().await?;
        let entity: Option<MetricsError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Returns 200 once the database is reachable and migrations have applied successfully. Initial-setup state (whether the default admin password has been changed) is reported as an informational field on the response but does NOT influence the status code: a 503 here would make Kubernetes restart the pod, terminating any `kubectl exec` session an operator is using to complete setup. See issue #889.  API mutations are separately gated by the setup middleware (`api::middleware::setup`) until setup is complete, so a 200 from this endpoint does not imply that write traffic will be accepted.
pub async fn readiness_check(configuration: &configuration::Configuration, ) -> Result<models::ReadyzResponse, Error<ReadinessCheckError>> {

    let uri_str = format!("{}/readyz", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ReadyzResponse`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ReadyzResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ReadinessCheckError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

