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

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

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").to_string();
    let image_url = format!("https://hanime-cdn.com/{}", endpoint);

    let upstream = match requester
        .get_ref()
        .clone()
        .get_raw_with_headers(
            image_url.as_str(),
            vec![("Referer".to_string(), "https://hanime.tv/".to_string())],
        )
        .await
    {
        Ok(response) => response,
        Err(_) => return Ok(web::HttpResponse::NotFound().finish()),
    };

    let status = upstream.status();
    let headers = upstream.headers().clone();

    // Read body from upstream
    let bytes = upstream.bytes().await.map_err(error::ErrorBadGateway)?;

    // Build response and forward headers
    let mut resp = Response::build(status);

    if let Some(ct) = headers.get(CONTENT_TYPE) {
        if let Ok(ct_str) = ct.to_str() {
            resp.set_header(CONTENT_TYPE, ct_str);
        }
    }
    if let Some(cl) = headers.get(CONTENT_LENGTH) {
        if let Ok(cl_str) = cl.to_str() {
            resp.set_header(CONTENT_LENGTH, cl_str);
        }
    }

    // Either zero-copy to ntex Bytes...
    // Ok(resp.body(NtexBytes::from(bytes)))

    // ...or simple & compatible:
    Ok(resp.body(bytes.to_vec()))
}
