use cors::Cors;
use once_cell::sync::OnceCell;
use sqlx::mysql::MySqlPoolOptions;
use sqlx::{MySql, Pool};
use std::env;

#[macro_use]
extern crate rocket;

mod controller;
mod cors;
mod model;
mod online_classroom;

pub mod json_result;

static DB: OnceCell<Pool<MySql>> = OnceCell::new();

pub fn db() -> &'static Pool<MySql> {
    DB.get().expect("DB not initialized")
}

#[launch]
async fn rocket() -> _ {
    dotenvy::dotenv().expect("Failed to load .env file");

    /*
       Init DB
    */
    let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
    let pool = MySqlPoolOptions::new()
        .max_connections(5)
        .connect(db_url.as_str())
        .await;

    match pool {
        Ok(pool) => DB.set(pool).expect("Failed to set DB pool"),
        Err(e) => println!("Error connecting to DB: {}", e),
    }

    /* Init Rocket */
    rocket::build().attach(Cors {}).mount(
        "/api",
        routes![
            controller::person::get_by_dni,
            controller::person::options,
            controller::person::create_person,
            controller::course::get_all,
            controller::register::insert_all,
            controller::register::options,
            controller::register::options_delete,
            controller::register::get_by_dni,
            controller::register::delete,
            controller::custom_label::get_all,
            //
            // Online classroom routes
            //
            online_classroom::connection,
            online_classroom::users::get_users,
        ],
    )
}
