/*
    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::{DATABASE, session::Session};
use anyhow::{Result, anyhow};
use jellycommon::{
    api::ApiAdminUsersResponse,
    user::{User, UserPermission},
};

pub fn admin_users(session: &Session) -> Result<ApiAdminUsersResponse> {
    session.assert_admin()?;
    // TODO dont return useless info like passwords
    Ok(ApiAdminUsersResponse {
        users: DATABASE.list_users()?,
    })
}
pub fn get_user(session: &Session, username: &str) -> Result<User> {
    session.assert_admin()?;
    DATABASE
        .get_user(username)?
        .ok_or(anyhow!("user not found"))
}
pub fn delete_user(session: &Session, username: &str) -> Result<()> {
    session.assert_admin()?;
    if !DATABASE.delete_user(username)? {
        Err(anyhow!("user did not exist"))?;
    }
    Ok(())
}

pub enum GrantState {
    Grant,
    Revoke,
    Unset,
}
pub fn update_user_perms(
    session: &Session,
    username: &str,
    perm: UserPermission,
    action: GrantState,
) -> Result<()> {
    session.assert_admin()?;
    DATABASE.update_user(username, |user| {
        match action {
            GrantState::Grant => drop(user.permissions.0.insert(perm.clone(), true)),
            GrantState::Revoke => drop(user.permissions.0.insert(perm.clone(), false)),
            GrantState::Unset => drop(user.permissions.0.remove(&perm)),
        }
        Ok(())
    })
}
