pub mod auth;
pub mod sync;
pub mod upgrade;

use anyhow::Result;
use auth::{load_token, TokenStore};
use upgrade::Tier;

pub struct CloudClient {
    pub endpoint: String,
    pub token: Option<TokenStore>,
}

impl CloudClient {
    pub fn new(endpoint: impl Into<String>) -> Self {
        Self {
            endpoint: endpoint.into(),
            token: None,
        }
    }

    /// Load from persisted token file (returns unauthenticated client if not logged in).
    pub fn from_env() -> Self {
        let endpoint = std::env::var("BCTX_CLOUD_ENDPOINT")
            .unwrap_or_else(|_| "https://api.betterctx.com".to_string());
        let token = load_token();
        Self { endpoint, token }
    }

    pub fn is_authenticated(&self) -> bool {
        self.token.is_some()
    }

    pub fn tier(&self) -> Tier {
        self.token
            .as_ref()
            .map(|t| Tier::parse_tier(&t.tier))
            .unwrap_or(Tier::Free)
    }

    pub fn bearer_token(&self) -> Option<&str> {
        self.token.as_ref().map(|t| t.access_token.as_str())
    }

    pub fn gate(&self, required: &Tier, feature: &str) -> Result<()> {
        upgrade::gate(&self.tier(), required, feature).map_err(|e| anyhow::anyhow!(e))
    }
}
