pub mod cache;
pub mod config;
pub mod db;
pub mod logger;

use anyhow::Context;
use neon_rs::redis::pool::SinglePool;
use sqlx::MySqlPool;

#[derive(Clone, Default)]
pub struct AppState {
    db_default: Option<MySqlPool>,
    redis_default: Option<SinglePool>,
}

impl AppState {
    pub async fn new() -> anyhow::Result<Self> {
        let db_default = db::new("db").await.context("DB(default) init failed")?;

        let redis_default = cache::new("redis").await.context("Redis(default) init failed")?;

        Ok(Self {
            db_default: Some(db_default),
            redis_default: Some(redis_default),
        })
    }

    pub fn db(&self) -> &sqlx::MySqlPool {
        self.db_default.as_ref().expect("DB(default) is None (forgotten initialize?)")
    }

    pub fn redis(&self) -> &SinglePool {
        self.redis_default
            .as_ref()
            .expect("Redis(default) is None (forgotten initialize?)")
    }
}
