/*
    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>
*/
#![feature(duration_constructors)]

pub mod account;
pub mod admin;
pub mod assets;
pub mod filter_sort;
pub mod home;
pub mod items;
pub mod login;
pub mod node;
pub mod permission;
pub mod search;
pub mod session;
pub mod stats;

use anyhow::Context;
use anyhow::Result;
use jellydb::Database;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::LazyLock;
use std::sync::Mutex;

#[rustfmt::skip]
#[derive(Debug, Deserialize, Serialize, Default)]
pub struct Config {
  login_expire: i64,
  session_key: Option<String>,
  admin_username:Option<String>,
  admin_password:Option<String>,
  database_path: PathBuf,
}

pub static CONF_PRELOAD: Mutex<Option<Config>> = Mutex::new(None);
static CONF: LazyLock<Config> = LazyLock::new(|| {
    CONF_PRELOAD
        .lock()
        .unwrap()
        .take()
        .expect("logic config not preloaded. logic error")
});

static DATABASE_PRELOAD: Mutex<Option<Database>> = Mutex::new(None);
static DATABASE: LazyLock<Database> = LazyLock::new(|| {
    DATABASE_PRELOAD
        .lock()
        .unwrap()
        .take()
        .expect("database not preloaded. logic error")
});

pub fn init_database() -> Result<()> {
    let database = Database::open(&CONF.database_path)
        .context("opening database")
        .unwrap();
    *DATABASE_PRELOAD.lock().unwrap() = Some(database);
    Ok(())
}
