use ntex::http::header::{CONTENT_LENGTH, CONTENT_TYPE};
use ntex::{
    http::Response,
    web::{self, HttpRequest, error},
};

use crate::util::requester::Requester;

const REFERER: &str = "https://hotbunny.ai/";

pub async fn get_image(
    req: HttpRequest,
    requester: web::types::State<Requester>,
) -> Result<impl web::Responder, web::Error> {
    let endpoint = req.match_info().query("endpoint").trim_start_matches('/');
    let image_url = if endpoint.starts_with("https://") || endpoint.starts_with("http://") {
        endpoint.to_string()
    } else {
        format!("https://{endpoint}")
    };

    let upstream = match requester
        .get_ref()
        .clone()
        .get_raw_with_headers(
            &image_url,
            vec![("Referer".to_string(), REFERER.to_string())],
        )
        .await
    {
        Ok(r) => r,
        Err(_) => return Ok(web::HttpResponse::NotFound().finish()),
    };

    let status = upstream.status();
    let headers = upstream.headers().clone();
    let bytes = upstream.bytes().await.map_err(error::ErrorBadGateway)?;

    let mut resp = Response::build(status);
    if let Some(ct) = headers.get(CONTENT_TYPE) {
        if let Ok(s) = ct.to_str() {
            resp.set_header(CONTENT_TYPE, s);
        }
    }
    if let Some(cl) = headers.get(CONTENT_LENGTH) {
        if let Ok(s) = cl.to_str() {
            resp.set_header(CONTENT_LENGTH, s);
        }
    }

    Ok(resp.body(bytes.to_vec()))
}
