/// Navigator API simulation.
///
/// Returns persona-configured values for all navigator properties.
/// Phishing kits check these to detect sandboxes.
///
use jsdet_core::observation::Value;

use crate::persona::Persona;

/// Get a navigator property value based on the persona.
pub fn get_navigator_property(persona: &Persona, property: &str) -> Value {
    match property {
        "userAgent" => Value::string(persona.user_agent.clone()),
        "platform" => Value::string(persona.platform.clone()),
        "language" => Value::string(persona.language.clone()),
        "languages" => Value::json(serde_json::to_string(&persona.languages).unwrap_or_default()),
        "hardwareConcurrency" => Value::Int(persona.hardware_concurrency as i64),
        "deviceMemory" => Value::Float(persona.device_memory),
        "maxTouchPoints" => Value::Int(persona.max_touch_points as i64),
        "vendor" => Value::string(persona.vendor.clone()),
        "appName" => Value::string(persona.app_name.clone()),
        "appVersion" => Value::string(persona.app_version.clone()),
        "doNotTrack" => match &persona.do_not_track {
            Some(v) => Value::string(v.clone()),
            None => Value::Null,
        },
        "cookieEnabled" => Value::Bool(true),
        "onLine" => Value::Bool(true),
        "webdriver" => Value::Bool(false), // Never expose sandbox
        "pdfViewerEnabled" => Value::Bool(true),
        "javaEnabled" => Value::Bool(false),
        "credentials" => Value::json(r#"{"create":"[native]","get":"[native]"}"#),
        "clipboard" => Value::json(r#"{"readText":"[native]","writeText":"[native]"}"#),
        "geolocation" => Value::json(r#"{"getCurrentPosition":"[native]"}"#),
        "mediaDevices" => Value::json(r#"{"enumerateDevices":"[native]"}"#),
        "permissions" => Value::json(r#"{"query":"[native]"}"#),
        "serviceWorker" => Value::json(r#"{"register":"[native]","ready":"[native]"}"#),
        "storage" => Value::json(r#"{"estimate":"[native]"}"#),
        "connection" => {
            Value::json(r#"{"effectiveType":"4g","downlink":10,"rtt":50,"saveData":false}"#)
        }
        "plugins" => Value::json("[]"),
        "mimeTypes" => Value::json("[]"),
        _ => Value::Undefined,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn webdriver_is_always_false() {
        let persona = Persona::default();
        assert_eq!(
            get_navigator_property(&persona, "webdriver"),
            Value::Bool(false)
        );
    }

    #[test]
    fn user_agent_matches_persona() {
        let persona = Persona::chrome_macos();
        let ua = get_navigator_property(&persona, "userAgent");
        assert!(matches!(ua, Value::String(s, _) if s.contains("Macintosh")));
    }
}
