use once_cell::sync::Lazy;
use surrealdb::engine::local::{Db, RocksDb};
use surrealdb::Surreal;

pub static DB: Lazy<Surreal<Db>> = Lazy::new(|| Surreal::init());

pub async fn initialize() -> surrealdb::Result<()> {
    DB.connect::<RocksDb>("./database").await?;

    DB.use_ns("xvmcmm").use_db("xvmcmm").await?;

    apply_queries().await?;

    Ok(())
}

async fn apply_queries() -> surrealdb::Result<()> {
    // Define user table
    DB.query(
        "
            DEFINE TABLE OVERWRITE user SCHEMAFULL;

            DEFINE FIELD email ON TABLE user TYPE string
                VALUE string::lowercase($value)
                ASSERT string::is::email($value);
            DEFINE FIELD password ON TABLE user TYPE string;

            DEFINE INDEX userEmailIndex ON TABLE user COLUMNS email UNIQUE;
        ",
    )
    .await?;

    DB.query(
        "
            DEFINE TABLE OVERWRITE user_to_member SCHEMAFULL TYPE RELATION FROM user TO member ENFORCED;
        ",
    )
    .await?;

    // Define session table
    DB.query(
        "
            DEFINE TABLE OVERWRITE session SCHEMAFULL;

            DEFINE FIELD user ON TABLE session TYPE record;
            DEFINE FIELD token ON TABLE session TYPE string
                VALUE rand::string(32);
            DEFINE FIELD expires ON TABLE session TYPE datetime
                VALUE time::now() + 1w;

            DEFINE INDEX sessionTokenIndex ON TABLE session COLUMNS token UNIQUE;
        ",
    )
    .await?;

    Ok(())
}
