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

use crate::{DATABASE, session::Session};
use anyhow::{Result, anyhow};
use jellyimport::{import_wrap, reporting::IMPORT_ERRORS};
use rand::Rng;
use tokio::{spawn, task::spawn_blocking};

pub async fn get_import_errors(_session: &Session) -> Vec<String> {
    IMPORT_ERRORS.read().await.to_owned()
}
pub fn list_invites(session: &Session) -> Result<Vec<String>> {
    session.assert_admin()?;
    DATABASE.list_invites()
}

pub fn create_invite(session: &Session) -> Result<String> {
    session.assert_admin()?;
    let i = format!("{}", rand::rng().random::<u128>());
    DATABASE.create_invite(&i)?;
    Ok(i)
}
pub fn delete_invite(session: &Session, invite: &str) -> Result<()> {
    session.assert_admin()?;
    if !DATABASE.delete_invite(invite)? {
        Err(anyhow!("invite does not exist"))?;
    };
    Ok(())
}
pub async fn update_search_index(session: &Session) -> Result<()> {
    session.assert_admin()?;
    spawn_blocking(move || DATABASE.search_create_index()).await?
}
pub async fn do_import(session: &Session, incremental: bool) -> Result<()> {
    session.assert_admin()?;
    if !incremental {
        DATABASE.clear_nodes()?;
    }
    spawn(import_wrap((*DATABASE).clone(), incremental));
    Ok(())
}
