use crate::Language;
use axum::http::HeaderMap;
use axum_extra::extract::CookieJar;

pub(crate) fn language(cookies: &CookieJar, headers: &HeaderMap) -> Language {
    if let Some(lang_cookie) = cookies.clone().get("language") {
        // Return existing language cookie
        lang_cookie.value().to_string().into()
    } else {
        // Extract language from Accept-Language header
        extract_preferred_language(headers).into()
    }
}

fn extract_preferred_language(headers: &HeaderMap) -> String {
    headers
        .get("accept-language")
        .and_then(|header| header.to_str().ok())
        .and_then(|accept_lang| {
            // Parse Accept-Language header (format: "en-US,en;q=0.9,fr;q=0.8")
            accept_lang
                .split(',')
                .next() // Get first (highest priority) language
                .map(|lang| {
                    lang.split(';')
                        .next() // Remove quality factor (q=0.9)
                        .unwrap_or(lang)
                        .trim()
                        .to_lowercase()
                })
        })
        .unwrap_or_else(|| "en".to_string()) // Default to English
}
