use ntex::web;
use url::Url;

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

#[derive(Debug, Clone)]
pub struct SupjavProxy {}

impl SupjavProxy {
    pub fn new() -> Self {
        Self {}
    }

    fn normalize_target(endpoint: &str) -> Option<String> {
        let endpoint = endpoint.trim().trim_start_matches('/');
        if endpoint.is_empty() {
            return None;
        }

        let target = if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
            endpoint.to_string()
        } else {
            format!("https://{endpoint}")
        };

        Self::is_allowed_media_url(&target).then_some(target)
    }

    fn is_allowed_media_url(url: &str) -> bool {
        let Some(parsed) = Url::parse(url).ok() else {
            return false;
        };
        if parsed.scheme() != "https" {
            return false;
        }

        let Some(host) = parsed.host_str() else {
            return false;
        };
        let host = host.to_ascii_lowercase();
        if !(host == "turbovidhls.com"
            || host == "turboviplay.com"
            || host == "turbosplayer.com"
            || host.ends_with(".turboviplay.com")
            || host.ends_with(".turbovidhls.com")
            || host.ends_with(".turbosplayer.com"))
        {
            return false;
        }

        parsed.path().to_ascii_lowercase().contains(".m3u8")
    }
}

impl crate::proxies::Proxy for SupjavProxy {
    async fn get_video_url(
        &self,
        url: String,
        _requester: web::types::State<Requester>,
    ) -> String {
        Self::normalize_target(&url).unwrap_or_default()
    }
}

