use std::collections::HashMap;
use std::thread;

use crate::types::{FetchFlagsRequest, FetchFlagsResponse, ReportRequest};

pub(crate) struct ApiClient {
    base_url: String,
    public_token: String,
}

impl ApiClient {
    pub fn new(base_url: String, public_token: String) -> Self {
        ApiClient {
            base_url,
            public_token,
        }
    }

    pub fn fetch_flags(
        &self,
        user_id: Option<String>,
        traits: Option<HashMap<String, String>>,
    ) -> Result<FetchFlagsResponse, String> {
        let url = format!("{}/api/sdk/flags", self.base_url);
        let body = FetchFlagsRequest { user_id, traits };
        let resp = ureq::post(&url)
            .set("Content-Type", "application/json")
            .set("Authorization", &format!("Bearer {}", self.public_token))
            .send_json(ureq::json!(body));

        match resp {
            Ok(response) => {
                let text = response.into_string().map_err(|e| e.to_string())?;
                let parsed: FetchFlagsResponse =
                    serde_json::from_str(&text).map_err(|e| e.to_string())?;
                Ok(parsed)
            }
            Err(e) => Err(format!("Failed to fetch flags: {}", e)),
        }
    }

    /// Fire-and-forget error report. Spawns a background thread.
    pub fn report_error(
        base_url: String,
        public_token: String,
        flag_name: String,
        message: String,
        stack: Option<String>,
        user_id: Option<String>,
        traits: Option<HashMap<String, String>>,
    ) {
        thread::spawn(move || {
            let url = format!("{}/api/sdk/report", base_url);
            let body = ReportRequest {
                flag_name,
                message,
                stack,
                user_id,
                traits,
            };
            let _ = ureq::post(&url)
                .set("Content-Type", "application/json")
                .set("Authorization", &format!("Bearer {}", public_token))
                .send_json(ureq::json!(body));
        });
    }
}

