// retrigger-build-marker
#![allow(dead_code)]

mod handlers;

use axum::{extract::DefaultBodyLimit, routing::get, Router};
use cache::RedisPool;
use std::net::SocketAddr;
use std::sync::Arc;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[derive(Clone)]
pub struct AppState {
    pub pool: sqlx::PgPool,
    pub storage: Arc<storage::StorageClient>,
    pub mail: Arc<email::Mailer>,
    pub redis: RedisPool,
}

#[tokio::main]
async fn main() {
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()),
        ))
        .with(tracing_subscriber::fmt::layer())
        .init();

    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = sqlx::postgres::PgPoolOptions::new()
        .max_connections(5)
        .connect(&database_url)
        .await
        .expect("Failed to connect to postgres");

    tracing::info!("Job Seekers service — connected to database");

    let storage = Arc::new(storage::StorageClient::from_env().await);
    let mailer = Arc::new(email::Mailer::new());

    let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL must be set");
    let redis = cache::connect(&redis_url).await.expect("Failed to connect to Redis");
    tracing::info!("Job Seekers service — connected to Redis");

    let state = AppState { pool, storage, mail: mailer, redis };

    let app = Router::new()
        .nest("/api/jobseeker", handlers::router())
        .route("/health", get(|| async { "Job Seekers OK" }))
        .layer(DefaultBodyLimit::max(11 * 1024 * 1024))
        .with_state(state);

    let port: u16 = std::env::var("PORT")
        .unwrap_or_else(|_| "9104".to_string())
        .parse()
        .expect("PORT must be a number");
    let addr = SocketAddr::from(([0, 0, 0, 0], port));

    tracing::info!("Job Seekers service listening on {}", addr);

    let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
