use std::sync::Arc;
use std::time::Duration;

use tokio::time;

use crate::news::service::NewsService;
use crate::news::types::{RefreshNewsFeedRequest, RefreshNewsFeedResult};

pub fn spawn_news_scheduler<F>(service: Arc<NewsService>, on_refresh: F)
where
    F: Fn(RefreshNewsFeedResult) + Send + Sync + 'static,
{
    let callback = Arc::new(on_refresh);
    tauri::async_runtime::spawn(async move {
        time::sleep(Duration::from_secs(5)).await;

        loop {
            if let Ok(result) = service
                .refresh_feed(RefreshNewsFeedRequest { force: Some(false) })
                .await
            {
                callback(result);
            }

            time::sleep(Duration::from_secs(15 * 60)).await;
        }
    });
}
