use reqwest::{Client, Error};
use serde::Serialize;
use crate::data_refresh;

pub struct HttpClient {
    client: Client,
}

impl HttpClient {
    pub fn new() -> Self {
        Self {
            client: Client::new(),
        }
    }

    /// GET request with authentication
    pub async fn get_with_auth(&self, url: &str) -> Result<String, Error> {
        let token = data_refresh(&"access");
        
        let response = self.client
            .get(url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await?
            .text()
            .await?;
        
        Ok(response)
    }

    /// POST request with JSON body and authentication
    pub async fn post_json_with_auth<T: Serialize>(&self, url: &str, json: &T) -> Result<String, Error> {
        let token = data_refresh(&"access");
        
        let response = self.client
            .post(url)
            .json(json)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await?
            .text()
            .await?;
        
        Ok(response)
    }

    /// DELETE request with authentication
    pub async fn delete_with_auth(&self, url: &str) -> Result<String, Error> {
        let token = data_refresh(&"access");
        
        let response = self.client
            .delete(url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await?
            .text()
            .await?;
        
        Ok(response)
    }

    /// POST request without authentication (for login, etc.)
    pub async fn post_json<T: Serialize>(&self, url: &str, json: &T) -> Result<String, Error> {
        let response = self.client
            .post(url)
            .json(json)
            .send()
            .await?
            .text()
            .await?;
        
        Ok(response)
    }

    /// GET request without authentication
    pub async fn get(&self, url: &str) -> Result<String, Error> {
        let response = self.client
            .get(url)
            .send()
            .await?
            .text()
            .await?;
        
        Ok(response)
    }

    /// POST request with custom headers
    pub async fn post_with_headers<T: Serialize>(
        &self, 
        url: &str, 
        json: &T,
        headers: Vec<(&str, &str)>
    ) -> Result<String, Error> {
        let mut request = self.client.post(url).json(json);
        
        for (key, value) in headers {
            request = request.header(key, value);
        }
        
        let response = request
            .send()
            .await?
            .text()
            .await?;
        
        Ok(response)
    }
}

impl Default for HttpClient {
    fn default() -> Self {
        Self::new()
    }
}