use std::str::FromStr;

use sqlx::migrate::Migrator;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Pool, Sqlite};

mod controllers;
pub mod errors;
mod junction_relay_schedule;
mod junction_tag;
mod model_utils;
mod relays;
mod schedules;
mod tag;

pub use controllers::DbController;
pub use junction_relay_schedule::DbJunctionRelaySchedule;
pub use junction_tag::DbJunctionTag;
pub use relays::DbRelay;
pub use schedules::{DbPeriods, DbSchedule};
pub use tag::DbTag;

static MIGRATOR: Migrator = sqlx::migrate!("../migrations"); // defaults to "./migrations"

pub async fn run_migrations(pool: &Pool<Sqlite>) {
	log::info!("Running migrations");
	MIGRATOR.run(pool).await.expect("Failed to run migrations.");
}

pub async fn init(db: &str) -> Pool<Sqlite> {
	let options = SqliteConnectOptions::from_str(db)
		.expect("Error parsing database path")
		.create_if_missing(true);

	let pool: Pool<Sqlite> = SqlitePoolOptions::new()
		.acquire_timeout(std::time::Duration::from_secs(1))
		.max_connections(5)
		.connect_with(options)
		.await
		.expect("Error connecting to database");

	run_migrations(&pool).await;

	let mut pool_conn = pool.acquire().await.unwrap();

	DbSchedule::get_on(&mut pool_conn)
		.await
		.expect("Failed to init 'on' schedule");
	DbSchedule::get_off(&mut pool_conn)
		.await
		.expect("Failed to init 'off' schedule");

	pool
}