/*
    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 crate::{
    State,
    auth::token_to_user,
    ui::error::{MyError, MyResult},
};
use anyhow::anyhow;
use jellycommon::{
    USER_ADMIN,
    jellyobject::{Object, ObjectBuffer},
};
use jellyui::RenderInfo;
use rocket::{
    Request, async_trait,
    http::{MediaType, Status},
    request::{FromRequest, Outcome},
};
use std::sync::Arc;

pub struct RequestInfo<'a> {
    pub lang: &'a str,
    pub accept: Accept,
    pub debug: &'a str,
    pub user: Option<ObjectBuffer>,
    pub state: Arc<State>,
}

#[async_trait]
impl<'r> FromRequest<'r> for RequestInfo<'r> {
    type Error = MyError;
    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        match Self::from_request_ut(request).await {
            Ok(a) => Outcome::Success(a),
            Err(a) => Outcome::Error((Status::BadRequest, a)),
        }
    }
}

impl<'a> RequestInfo<'a> {
    pub async fn from_request_ut(request: &'a Request<'_>) -> MyResult<Self> {
        let state: &Arc<State> = request.rocket().state().unwrap();
        Ok(Self {
            lang: accept_language(request),
            accept: Accept::from_request_ut(request),
            user: user_from_request(state, request)?,
            state: state.clone(),
            debug: request
                .query_value::<&str>("debug")
                .transpose()
                .unwrap()
                .unwrap_or("none"),
        })
    }
    pub fn require_user(&'a self) -> MyResult<Object<'a>> {
        self.user
            .as_ref()
            .map(|u| u.as_object())
            .ok_or(MyError(anyhow!("user required")))
    }
    pub fn require_admin(&'a self) -> MyResult<Object<'a>> {
        let user = self.require_user()?;
        if !user.has(USER_ADMIN.0) {
            Err(anyhow!("admin required"))?
        }
        Ok(user)
    }
    pub fn render_info(&'a self) -> RenderInfo<'a> {
        RenderInfo {
            lang: self.lang,
            status_message: None,
            user: self.user.as_ref().map(|u| u.as_object()),
            config: &self.state.config.ui,
        }
    }
}

#[derive(Debug, Default)]
pub enum Accept {
    #[default]
    Other,
    Json,
    Image,
    Media,
    Html,
}
impl Accept {
    pub fn from_request_ut(request: &Request) -> Self {
        if let Some(a) = request.accept() {
            if a.preferred().exact_eq(&MediaType::JSON) {
                Accept::Json
            } else {
                Accept::Other
            }
        } else {
            Accept::Other
        }
    }

    pub fn is_json(&self) -> bool {
        matches!(self, Self::Json)
    }
}

fn accept_language<'a>(request: &'a Request<'_>) -> &'a str {
    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;
                    Some(code)
                })
                .next()
        })
        .unwrap_or("en")
}

fn user_from_request(state: &State, req: &Request<'_>) -> Result<Option<ObjectBuffer>, MyError> {
    let Some(token) = req
        .query_value("session")
        .map(|e| e.unwrap())
        .or_else(|| req.query_value("api_key").map(|e| e.unwrap()))
        .or_else(|| req.headers().get_one("X-MediaBrowser-Token"))
        .or_else(|| {
            req.headers()
                .get_one("Authorization")
                .and_then(parse_jellyfin_auth)
        }) // for jellyfin compat
        .or(req.cookies().get("session").map(|cookie| cookie.value()))
    else {
        return Ok(None);
    };

    // jellyfin urlescapes the token for *some* requests
    let token = token.replace("%3D", "=");
    Ok(Some(token_to_user(state, &token)?))
}

fn parse_jellyfin_auth(h: &str) -> Option<&str> {
    for tok in h.split(" ") {
        if let Some(tok) = tok.strip_prefix("Token=\"")
            && let Some(tok) = tok.strip_suffix("\"")
        {
            return Some(tok);
        }
    }
    None
}
