use sqlx::PgPool;

pub async fn record_bot_metrics(db: PgPool) {
    let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
    loop {
        interval.tick().await;

        if let Ok(row) = sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM bots")
            .fetch_one(&db)
            .await
        {
            metrics::gauge!("irc_now_bots_total").set(row.0 as f64);
        }

        if let Ok(row) =
            sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM bots WHERE enabled = true")
                .fetch_one(&db)
                .await
        {
            metrics::gauge!("irc_now_bots_enabled").set(row.0 as f64);
        }

        if let Ok(row) =
            sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM bots WHERE status = 'running'")
                .fetch_one(&db)
                .await
        {
            metrics::gauge!("irc_now_bots_running").set(row.0 as f64);
        }

        if let Ok(row) = sqlx::query_as::<_, (i64,)>(
            "SELECT COUNT(*) FROM bot_logs WHERE level = 'error' AND created_at > NOW() - INTERVAL '24 hours'",
        )
        .fetch_one(&db)
        .await
        {
            metrics::gauge!("irc_now_bot_errors_24h").set(row.0 as f64);
        }

        if let Ok(row) = sqlx::query_as::<_, (i64,)>(
            "SELECT COUNT(*) FROM bot_scripts WHERE enabled = true",
        )
        .fetch_one(&db)
        .await
        {
            metrics::gauge!("irc_now_bot_scripts_enabled").set(row.0 as f64);
        }
    }
}
