/*
    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>
*/
pub mod import;
pub mod log;
pub mod user;

use super::error::MyResult;
use crate::helper::RequestInfo;
use jellycommon::routes::u_admin_dashboard;
use jellyimport::is_importing;
use jellylogic::admin::{create_invite, delete_invite, list_invites, update_search_index};
use jellyui::{admin::AdminDashboardPage, locale::tr, render_page};
use rocket::{
    FromForm,
    form::Form,
    get, post,
    request::FlashMessage,
    response::{Flash, Redirect, content::RawHtml},
};

#[get("/admin/dashboard")]
pub async fn r_admin_dashboard(
    ri: RequestInfo,
    flash: Option<FlashMessage<'_>>,
) -> MyResult<RawHtml<String>> {
    ri.session.assert_admin()?;
    let invites = list_invites(&ri.session)?;

    let busy = if is_importing() {
        Some("An import is currently running.")
    } else {
        None
    };

    Ok(RawHtml(render_page(
        &AdminDashboardPage {
            busy,
            invites: &invites,
            flash: &flash.map(FlashMessage::into_inner),
            lang: &ri.lang,
        },
        ri.render_info(),
    )))
}

#[post("/admin/generate_invite")]
pub async fn r_admin_invite(ri: RequestInfo) -> MyResult<Flash<Redirect>> {
    let i = create_invite(&ri.session)?;
    Ok(Flash::success(
        Redirect::to(u_admin_dashboard()),
        tr(ri.lang, "admin.invite_create_success").replace("{invite}", &i),
    ))
}

#[derive(FromForm)]
pub struct DeleteInvite {
    invite: String,
}

#[post("/admin/remove_invite", data = "<form>")]
pub async fn r_admin_remove_invite(
    ri: RequestInfo,
    form: Form<DeleteInvite>,
) -> MyResult<Flash<Redirect>> {
    ri.session.assert_admin()?;
    delete_invite(&ri.session, &form.invite)?;
    Ok(Flash::success(
        Redirect::to(u_admin_dashboard()),
        tr(ri.lang, "admin.invite_delete_success"),
    ))
}

#[post("/admin/update_search")]
pub async fn r_admin_update_search(ri: RequestInfo) -> MyResult<Flash<Redirect>> {
    ri.session.assert_admin()?;
    update_search_index(&ri.session).await?;
    Ok(Flash::success(
        Redirect::to(u_admin_dashboard()),
        tr(ri.lang, "admin.update_search_success"),
    ))
}
