use crate::web::RequestOrigin;
use crate::web::templates::Bare;
use crate::web::templates::HagridLayout;
use rocket::http::Status;
use rocket::response::status::Custom;
use rocket_codegen::get;
use rocket_dyn_templates::Template;
use rocket_i18n::I18n;

#[get("/errors/<code>/<template>")]
pub fn errors(
    i18n: I18n,
    origin: RequestOrigin,
    code: u16,
    template: String,
) -> Result<Custom<Template>, &'static str> {
    if !template
        .chars()
        .all(|x| x == '-' || char::is_ascii_alphabetic(&x))
    {
        return Err("bad request");
    }
    let status_code = Status::from_code(code).ok_or("bad request")?;
    let response_body = Template::render(
        format!("errors/{}-{}", code, template),
        HagridLayout::new(Bare { dummy: () }, i18n, origin),
    );
    Ok(Custom(status_code, response_body))
}
