//! Typed app discovery.
//!
//! An app is the billing and ownership scope a sailbox belongs to. Look one up
//! by name with [`Client::find_app`](crate::Client::find_app) or list the
//! org's apps with [`Client::list_apps`](crate::Client::list_apps); both map
//! failures onto the canonical [`SailError`] taxonomy.

use serde::Serialize;
use serde_json::{json, Value};
use time::OffsetDateTime;

use crate::error::SailError;
use crate::http::{HttpCore, IdempotencyKey, Method, RequestSpec};
use crate::retry::DEFAULT_RETRY_POLICY;

/// A Sail application.
#[derive(Debug, Clone, Serialize)]
pub struct App {
    /// Stable server-assigned app identifier.
    pub id: String,
    /// Human-readable app name unique within the owning org.
    pub name: String,
    /// App creation time.
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
}

impl App {
    /// Parse an app row from an API response object, defaulting missing fields.
    fn from_json(row: &Value) -> App {
        App {
            id: row
                .get("id")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            name: row
                .get("name")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            // Arrives as a Unix integer; re-serialized as RFC 3339 like every
            // other bindings timestamp.
            created_at: OffsetDateTime::from_unix_timestamp(
                row.get("created_at").and_then(Value::as_i64).unwrap_or(0),
            )
            .unwrap_or(OffsetDateTime::UNIX_EPOCH),
        }
    }
}

/// Find an app by name on the central API, optionally minting it.
pub(crate) async fn find_app(
    api_http: &HttpCore,
    name: &str,
    mint_if_missing: bool,
) -> Result<App, SailError> {
    let body = json!({ "name": name, "mint_if_missing": mint_if_missing });
    let bytes = serde_json::to_vec(&body).map_err(|e| SailError::Internal {
        message: format!("failed to serialize request body: {e}"),
    })?;
    let (status, data) = api_http
        .request(&RequestSpec {
            method: Method::Post,
            path: "/v1/apps/find".to_string(),
            query: Vec::new(),
            body: Some(bytes),
            extra_headers: Vec::new(),
            timeout: None,
            policy: DEFAULT_RETRY_POLICY,
            idempotency_key: IdempotencyKey::Auto,
        })
        .await?;
    // find returns 404 for any miss (not type-gated, unlike sailbox lookups).
    if status == 404 {
        return Err(SailError::NotFound {
            message: format!("App {name:?} not found"),
        });
    }
    raise_app_error(status, &data, "Failed to find app")?;
    Ok(App::from_json(&data))
}

/// Every app the org owns, newest first, from the central app index.
///
/// Reads the canonical apps table, so apps with no sailboxes yet are included.
/// The response is not paginated; the per-org app count is small.
pub(crate) async fn list_apps(api_http: &HttpCore) -> Result<Vec<App>, SailError> {
    let (status, data) = api_http
        .request(&RequestSpec {
            method: Method::Get,
            path: "/v1/apps".to_string(),
            query: Vec::new(),
            body: None,
            extra_headers: Vec::new(),
            timeout: None,
            policy: DEFAULT_RETRY_POLICY,
            idempotency_key: IdempotencyKey::Auto,
        })
        .await?;
    raise_app_error(status, &data, "Failed to list apps")?;
    let Some(rows) = data.get("data").and_then(Value::as_array) else {
        return Ok(Vec::new());
    };
    Ok(rows.iter().map(App::from_json).collect())
}

/// App ladder: 401/403 → PermissionDenied, any other non-2xx → Api
/// (transient/unexpected). 404 is handled by the caller where it is meaningful.
fn raise_app_error(status: u16, data: &Value, context: &str) -> Result<(), SailError> {
    if status < 300 {
        return Ok(());
    }
    let detail = crate::http::api_error_message(data, "unknown error");
    let message = format!("{context}: {detail}");
    if status == 401 || status == 403 {
        return Err(SailError::PermissionDenied { message });
    }
    Err(SailError::Api {
        status,
        message,
        body: data.clone(),
    })
}
