use std::collections::HashMap;
use std::time::Instant;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct HttpResponse {
    status: u16,
    headers: HashMap<String, String>,
    body: String,
    time_elapsed: u128, // milliseconds
}

#[derive(Serialize, Deserialize, Debug)]
struct BasicAuth {
    username: String,
    password: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct BearerAuth {
    token: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct ApiKeyAuth {
    key: String,
    value: String,
    #[serde(rename = "addTo")]
    add_to: String, // "header" or "query"
}

#[derive(Serialize, Deserialize, Debug)]
struct AuthConfig {
    #[serde(rename = "type")]
    auth_type: String, // "none", "basic", "bearer", "api_key"
    basic: BasicAuth,
    bearer: BearerAuth,
    #[serde(rename = "apiKey")]
    api_key: ApiKeyAuth,
}

#[tauri::command]
async fn execute_request(
    method: String,
    url: String,
    headers: HashMap<String, String>,
    body: Option<String>,
    query_params: Option<HashMap<String, String>>,
    auth: Option<AuthConfig>,
) -> Result<HttpResponse, String> {
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .build()
        .map_err(|e| e.to_string())?;

    let req_method = method.parse::<reqwest::Method>().map_err(|e| e.to_string())?;

    let mut request_builder = client.request(req_method, &url);

    // Add Query Params
    if let Some(params) = query_params {
        request_builder = request_builder.query(&params);
    }

    // Add Headers
    for (key, value) in headers {
        request_builder = request_builder.header(key, value);
    }

    // Add Auth
    if let Some(auth_config) = auth {
        match auth_config.auth_type.as_str() {
            "basic" => {
                request_builder = request_builder.basic_auth(
                    auth_config.basic.username,
                    Some(auth_config.basic.password),
                );
            }
            "bearer" => {
                request_builder = request_builder.bearer_auth(auth_config.bearer.token);
            }
            "api_key" => {
                let key = auth_config.api_key.key;
                let value = auth_config.api_key.value;
                if auth_config.api_key.add_to == "header" {
                    request_builder = request_builder.header(key, value);
                } else if auth_config.api_key.add_to == "query" {
                    request_builder = request_builder.query(&[(key, value)]);
                }
            }
            _ => {} // "none" or unknown
        }
    }

    // Add Body
    if let Some(b) = body {
        if !b.is_empty() {
             request_builder = request_builder.body(b);
        }
    }

    let start_time = Instant::now();
    // Execute request
    let response = request_builder.send().await.map_err(|e| e.to_string())?;
    let time_elapsed = start_time.elapsed().as_millis();

    let status = response.status().as_u16();
    
    let mut response_headers = HashMap::new();
    for (key, value) in response.headers() {
        // Handle header value to string conversion (skipping non-utf8 for simplicity or lossy conv)
        let val_str = value.to_str().unwrap_or("").to_string();
        // Capitalize or keep standard key format? keeping standard.
        response_headers.insert(key.to_string(), val_str);
    }

    let body_text = response.text().await.map_err(|e| e.to_string())?;

    Ok(HttpResponse {
        status,
        headers: response_headers,
        body: body_text,
        time_elapsed,
    })
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![execute_request])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}