use crate::repository::api::prelude::*;
use color_eyre::Result;
use serde::{Deserialize, Serialize};

pub async fn is_support(tg_id: i64) -> Result<bool> {
    let user_id = get_test_user_id(tg_id);
    #[derive(Serialize)]
    struct IsAdminData {
        user_id: String,
    }

    let auth_token = get_auth_token().await?;

    let url = format!("{}/rpc/tg.is_support", *BACKEND_API_URL);
    log::trace!("fetching {url}", url = url.red());
    let response = reqwest::Client::new()
        .post(&url)
        .header("Authorization", auth_token)
        .header("Content-Type", "application/json")
        .header("Content-Profile", "vgate")
        .json(&IsAdminData { user_id })
        .send()
        .await;

    log::debug!("response: {:?}", response);

    #[derive(Deserialize)]
    struct IsAdminResponse {
        is_support: bool,
    }

    match response {
        Ok(response) => match response.status() {
            reqwest::StatusCode::OK => {
                let is_support =
                    response.json::<IsAdminResponse>().await?.is_support;
                Ok(is_support)
            }
            _ => Err(Report::msg(format!(
                "Failed to get admin status: {}\n{:#?}",
                response.status(),
                response.headers(),
            ))),
        },
        Err(e) => {
            Err(Report::msg(format!("Failed to get admin status: {:?}", e)))
        }
    }
}