/*
    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 rocket::{
    http::MediaType,
    outcome::Outcome,
    request::{self, FromRequest},
    Request,
};
use std::ops::Deref;

#[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)
    }
}

pub struct AcceptJson(bool);
impl Deref for AcceptJson {
    type Target = bool;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<'r> FromRequest<'r> for AcceptJson {
    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(AcceptJson(matches!(
                Accept::from_request_ut(request),
                Accept::Json
            )))
        })
    }
}
