#![allow(dead_code)]

mod handlers;
mod admin;

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

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

#[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!("Customers service — connected to database");

    let mailer = Arc::new(email::Mailer::new());
    let storage = Arc::new(storage::StorageClient::from_env().await);
    let state = AppState { pool, mail: mailer, storage };

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

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

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

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