/*
    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::{helper::RequestInfo, ui::error::MyResult};
use anyhow::Context;
use jellycommon::{
    routes::{u_admin_user, u_admin_users},
    user::UserPermission,
};
use jellylogic::admin::user::{admin_users, delete_user, get_user, update_user_perms, GrantState};
use jellyui::{
    admin::user::{AdminUserPage, AdminUsersPage},
    locale::tr,
    render_page,
};
use rocket::{
    form::Form,
    get, post,
    response::{content::RawHtml, Flash, Redirect},
    FromForm, FromFormField,
};

#[get("/admin/users")]
pub fn r_admin_users(ri: RequestInfo) -> MyResult<RawHtml<String>> {
    ri.session.assert_admin()?;
    let r = admin_users(&ri.session)?;
    Ok(RawHtml(render_page(
        &AdminUsersPage {
            flash: &None,
            lang: &ri.lang,
            users: &r.users,
        },
        ri.render_info(),
    )))
}

#[get("/admin/user/<name>")]
pub fn r_admin_user(ri: RequestInfo, name: &str) -> MyResult<RawHtml<String>> {
    ri.session.assert_admin()?;
    let user = get_user(&ri.session, name)?;

    Ok(RawHtml(render_page(
        &AdminUserPage {
            flash: &None,
            lang: &ri.lang,
            user: &user,
        },
        ri.render_info(),
    )))
}

#[derive(FromForm)]
pub struct UserPermissionForm {
    permission: String,
    action: UrlGrantState,
}

#[derive(FromFormField)]
pub enum UrlGrantState {
    Grant,
    Revoke,
    Unset,
}

#[post("/admin/user/<name>/update_permission", data = "<form>")]
pub fn r_admin_user_permission(
    ri: RequestInfo,
    form: Form<UserPermissionForm>,
    name: &str,
) -> MyResult<Flash<Redirect>> {
    ri.session.assert_admin()?;
    let perm = serde_json::from_str::<UserPermission>(&form.permission)
        .context("parsing provided permission")?;

    update_user_perms(
        &ri.session,
        name,
        perm,
        match form.action {
            UrlGrantState::Grant => GrantState::Grant,
            UrlGrantState::Revoke => GrantState::Revoke,
            UrlGrantState::Unset => GrantState::Unset,
        },
    )?;

    Ok(Flash::success(
        Redirect::to(u_admin_user(name)),
        tr(ri.lang, "admin.users.permission_update_success"),
    ))
}

#[post("/admin/<name>/remove")]
pub fn r_admin_remove_user(ri: RequestInfo, name: &str) -> MyResult<Flash<Redirect>> {
    ri.session.assert_admin()?;
    delete_user(&ri.session, name)?;
    Ok(Flash::success(
        Redirect::to(u_admin_users()),
        tr(ri.lang, "admin.users.remove_success"),
    ))
}
