/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use jellyui::locale::Language;
use rocket::{
    outcome::Outcome,
    request::{self, FromRequest},
    Request,
};
use std::ops::Deref;

pub struct AcceptLanguage(pub Language);
impl Deref for AcceptLanguage {
    type Target = Language;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<'r> FromRequest<'r> for AcceptLanguage {
    type Error = ();

    fn from_request<'life0, 'async_trait>(
        request: &'r Request<'life0>,
    ) -> ::core::pin::Pin<
        Box<
            dyn ::core::future::Future<Output = request::Outcome<Self, Self::Error>>
                + ::core::marker::Send
                + 'async_trait,
        >,
    >
    where
        'r: 'async_trait,
        'life0: 'async_trait,
        Self: 'async_trait,
    {
        Box::pin(async move { Outcome::Success(AcceptLanguage(lang_from_request(request))) })
    }
}

pub(crate) fn lang_from_request(request: &Request) -> Language {
    request
        .headers()
        .get_one("accept-language")
        .and_then(|h| {
            h.split(",")
                .filter_map(|e| {
                    let code = e.split(";").next()?;
                    let code = code.split_once("-").unwrap_or((code, "")).0;
                    match code {
                        "en" => Some(Language::English),
                        "de" => Some(Language::German),
                        _ => None,
                    }
                })
                .next()
        })
        .unwrap_or(Language::English)
}
