use rocket::{Request, http::Status};
use rocket_dyn_templates::Template;
use serde::Serialize;

#[derive(Serialize)]
struct ErrorContext {
    error_code: u16,
    error_message: &'static str,
    additional_info: &'static str,
    redirect: Option<RedirectContext>,
}

#[derive(Serialize)]
struct RedirectContext {
    url: &'static str,
    message: &'static str,
}

#[catch(404)]
pub async fn handle_404() -> Template {
    Template::render(
        "error",
        ErrorContext {
            error_code: 404,
            error_message: "Not Found",
            additional_info: "There's nothing here.",
            redirect: Some(RedirectContext {
                url: "/",
                message: "Home",
            }),
        },
    )
}

#[catch(401)]
pub async fn handle_401() -> Template {
    Template::render(
        "error",
        ErrorContext {
            error_code: 401,
            error_message: "Unauthorised",
            additional_info: "You are not authorised to access this resource.",
            redirect: Some(RedirectContext {
                url: "/login",
                message: "Login",
            }),
        },
    )
}

#[catch(default)]
pub async fn handle_default(status: Status, _request: &Request<'_>) -> Template {
    Template::render(
        "error",
        ErrorContext {
            error_code: status.code,
            error_message: "Unknown Error",
            additional_info: "I don't know what to do with this error.",
            redirect: None,
        },
    )
}
