use crate::app_config::AppConfig;
use crate::services::{files_service, tokens_service};
use std::time::Duration;

/// The "cron" of the project
pub async fn main_routine() {
    loop {
        tokio::time::sleep(Duration::from_secs(AppConfig::get().routine_interval)).await;

        log::info!("Start to execute regular routine");
        match exec_routine().await {
            Ok(_) => {
                log::info!("Routine successfully executed")
            }
            Err(e) => {
                log::error!("Failed to execute routine! {e}");
            }
        }
    }
}

async fn exec_routine() -> anyhow::Result<()> {
    // Remove orphan attachments
    files_service::run_garbage_collector().await?;

    // Remove expired tokens
    tokens_service::cleanup().await?;

    Ok(())
}
