//! Billing sub-client — usage, checkout URL, portal URL.

use crate::client::Kranth;
use crate::errors::Result;
use crate::types::Usage;

pub struct BillingResource<'a> {
    pub(crate) client: &'a Kranth,
}

#[derive(Debug, Clone)]
pub struct CheckoutParams {
    pub plan: String,
    pub billing_period: Option<String>,
    pub success_url: Option<String>,
    pub cancel_url: Option<String>,
}

impl<'a> BillingResource<'a> {
    pub async fn usage(&self) -> Result<Usage> {
        self.client.get("/v1/usage", &[]).await
    }

    pub async fn checkout_url(&self, p: CheckoutParams) -> Result<String> {
        #[derive(serde::Deserialize)]
        struct Wrap {
            url: String,
        }
        let body = serde_json::json!({
            "plan":           p.plan,
            "billing_period": p.billing_period.unwrap_or_else(|| "monthly".into()),
            "success_url":    p.success_url,
            "cancel_url":     p.cancel_url,
        });
        let w: Wrap = self
            .client
            .post("/v1/billing/checkout", &body, None)
            .await?;
        Ok(w.url)
    }

    pub async fn portal_url(&self, return_url: Option<&str>) -> Result<String> {
        #[derive(serde::Deserialize)]
        struct Wrap {
            url: String,
        }
        let body = serde_json::json!({ "return_url": return_url });
        let w: Wrap = self.client.post("/v1/billing/portal", &body, None).await?;
        Ok(w.url)
    }
}
