use std::time::Duration;
use tokio::task::JoinHandle;
use tracing::error;

use crate::repositories::{AddressRepository, ApiKeyRepository, CountryRepository};
use crate::services::{ApiKeyCache, IngestionService};

/// Spawn a background task that periodically fetches sanctions data and upserts to the DB.
pub fn create_ingestion_worker(
    ingestion: IngestionService,
    address_repo: impl AddressRepository + 'static,
    country_repo: impl CountryRepository + 'static,
    interval: Duration,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            if let Err(e) = ingestion.run_cycle(&address_repo, &country_repo).await {
                error!(error = %e, "ingestion cycle failed");
            }
            tokio::time::sleep(interval).await;
        }
    })
}

/// Spawn a background task that periodically refreshes the API key cache from the DB.
pub fn create_api_key_refresh_worker(
    cache: ApiKeyCache,
    repo: impl ApiKeyRepository + 'static,
    interval: Duration,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            cache.refresh(&repo).await;
            tokio::time::sleep(interval).await;
        }
    })
}
