pub mod redis;
pub mod types;
pub mod worker;

pub use redis::RedisConsumer;
pub use types::{HookTask, PoolConfig, TaskType};
pub use worker::HookWorker;

use db::cache::AppCache;
use db::database::AppDatabase;
use deadpool_redis::cluster::Pool as RedisPool;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

/// Start the hook worker background task.
/// Returns a handle to the cancellation token so the caller can shut it down.
pub fn start_worker(
    db: AppDatabase,
    cache: AppCache,
    redis_pool: RedisPool,
    config: PoolConfig,
) -> CancellationToken {
    let consumer = RedisConsumer::new(
        redis_pool.clone(),
        config.redis_list_prefix.clone(),
        config.redis_block_timeout_secs,
    );

    let http_client = Arc::new(reqwest::Client::new());
    let max_retries = config.redis_max_retries as u32;
    let worker = HookWorker::new(db, cache, consumer, http_client, max_retries);

    let cancel = CancellationToken::new();
    let cancel_clone = cancel.clone();

    tokio::spawn(async move {
        worker.run(cancel_clone).await;
    });

    cancel
}
