use reqwest::{
    Client,
    header::{HeaderMap, HeaderValue},
};

pub async fn download_file(url: &str, _path: &str) -> Result<String, Box<dyn std::error::Error>> {
    // Some simple CLI args requirements...

    // reqwest::blocking::get() is a convenience function.
    //
    // In most cases, you should create/build a reqwest::Client and reuse
    // it for all requests.
    let res = reqwest::get(url).await?;

    let body = res.text().await?;
    Ok(body)
}

pub async fn validate_url(url: &str) -> bool {
    // Check if the URL is valid
    let parsed_url = url::Url::parse(url);

    if parsed_url.is_err() {
        eprintln!("Invalid URL: {}", url);
        return false;
    }

    let parsed_url = parsed_url.unwrap();

    // Check if the URL has a valid scheme
    if !["http", "https"].contains(&parsed_url.scheme()) {
        eprintln!("Unsupported URL scheme: {}", parsed_url.scheme());
        return false;
    }

    let client = Client::builder()
        .danger_accept_invalid_certs(true)
        .build()
        .unwrap_or_default();

    let response = client
        .get(parsed_url.as_str())
        .headers(construct_headers())
        .send()
        .await;

    match response {
        Ok(resp) => {
            println!(
                "StatusCode: {} {}",
                resp.status(),
                resp.status().is_success()
            );
            resp.status().is_success()
        }
        Err(err) => {
            println!("code:{},error:{}", err.status().unwrap_or_default(), err);
            false
        }
    }
}

fn construct_headers() -> HeaderMap {
    let mut headers = HeaderMap::new();
    headers.insert("User-Agent", HeaderValue::from_static("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"));
    headers.insert("Accept", HeaderValue::from_static("text/html"));
    headers.insert(
        "Referer",
        HeaderValue::from_static("https://www.google.com"),
    );
    headers
}
