use clap::Parser;
use config::AppConfig;
use observability::init_tracing_subscriber;
use service::AppService;

#[derive(Parser, Debug)]
#[command(name = "email-worker")]
#[command(version)]
struct Args {
    #[arg(long, default_value = "info")]
    log_level: String,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let args = Args::parse();
    let cfg = AppConfig::load();
    init_tracing_subscriber(&args.log_level);

    tracing::info!("Starting email worker");
    let service = AppService::new(cfg).await?;

    let (shutdown_tx, shutdown_rx) = tokio::sync::broadcast::channel::<()>(1);
    tokio::spawn(async move {
        tokio::signal::ctrl_c().await.ok();
        tracing::info!("shutting down email worker");
        let _ = shutdown_tx.send(());
    });

    service.start_email_workers(shutdown_rx).await?;
    tracing::info!("email worker stopped");
    Ok(())
}
