use std::collections::HashMap;

use reqwest::{Client, Proxy};
use serde_json::json;

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct FlareSolverrRequest {
    pub cmd: String,
    pub url: String,
    pub maxTimeout: u32,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct FlaresolverrCookie {
    name: String,         //"cf_clearance",
    value: String, //"lnKoXclrIp_mDrWJFfktPGm8GDyxjSpzy9dx0qDTiRg-1748689259-1.2.1.1-AIFERAPCdCSvvdu1mposNdUpKV9wHZXBpSI2L9k9TaKkPcqmomON_XEb6ZtRBtrmQu_DC8AzKllRg2vNzVKOUsvv9ndjQ.vv8Z7cNkgzpIbGFy96kXyAYH2mUk3Q7enZovDlEbK5kpV3Sbmd2M3_bUCBE1WjAMMdXlyNElH1LOpUm149O9hrluXjAffo4SwHI4HO0UckBPWBlBqhznKPgXxU0g8VHLDeYnQKViY8rP2ud4tyzKnJUxuYXzr4aWBNMp6TESp49vesRiel_Y5m.rlTY4zSb517S9iPbEQiYHRI.uH5mMHVI3jvJl0Mx94tPrpFnkhDdmzL3DRSllJe9k786Lf21I9WBoH2cCR3yHw",
    domain: String, //".discord.com",
    path: String,  //"/",
    expires: f64,  //1780225259.237105,
    size: u64,     //438,
    httpOnly: bool, //true,
    secure: bool,  //true,
    session: bool, //false,
    sameSite: Option<String>, //"None",
    priority: String, //"Medium",
    sameParty: bool, //false,
    sourceScheme: String, //"Secure",
    sourcePort: u32, //443,
    partitionKey: Option<String>, //"https://perverzija.com"
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]  
pub struct FlareSolverrSolution {
    url: String, 
    status: u32,
    pub response: String, 
    headers: HashMap<String, String>,
    cookies: Vec<FlaresolverrCookie>, 
    userAgent: String,
}
// impl FlareSolverrSolution {
//     fn to_client(&self,){
//         let mut headers = header::HeaderMap::new();
//         for (h, v) in &self.headers {
//             println!("{}: {}", h, v);
//             headers.insert(
//                 header::HeaderName::from_bytes(h.as_bytes()).unwrap(),
//                 header::HeaderValue::from_str(v).unwrap(),
//             );
//         }
//         // let client = reqwest::Client::builder()
//         //     .danger_accept_invalid_certs(true)
//         //     .
//         //     .build().unwrap();
//     }
// }
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct FlareSolverrResponse {
    status: String,
    message: String,
    pub solution: FlareSolverrSolution,
    startTimestamp: u64,
    endTimestamp: u64,
    version: String,
}
pub struct Flaresolverr {
    url: String
}
impl Flaresolverr {
    pub fn new(url: String) -> Self {
        Flaresolverr { 
            url: url
        }
    }

    pub async fn solve(
        &self,
        request: FlareSolverrRequest,
    ) -> Result<FlareSolverrResponse, Box<dyn std::error::Error>> {
            let client = Client::builder()
            .proxy(Proxy::https("http://192.168.0.101:8080").unwrap())
            .proxy(Proxy::http("http://192.168.0.101:8080").unwrap())
            .danger_accept_invalid_certs(true)
            .build()?;

    let response = client
        .post(&self.url)
        .header("Content-Type", "application/json")
        .json(&json!({
            "cmd": request.cmd,
            "url": request.url,
            "maxTimeout": request.maxTimeout,
        }))
        .send().await?;

    let body: FlareSolverrResponse = response.json::<FlareSolverrResponse>().await?;
    Ok(body)
    }
}
