use axum::{
    routing::{get, post},
    Router,
};
use std::net::SocketAddr;
use tower_http::{services::ServeDir, cors::CorsLayer};
use tracing::info;
use tracing_subscriber::fmt::init;

mod handlers;
mod models;
mod services;
mod layout;

use handlers::*;

#[tokio::main]
async fn main() {
    dotenvy::dotenv().ok();
    
    init();

    let app = Router::new()
        .route("/", get(home::home_handler))
        .route("/about", get(about::about_handler))
        .route("/ministries", get(ministries::ministries_handler))
        .route("/sermons", get(sermons::sermons_handler))
        .route("/sermons/:id", get(sermons::sermon_detail_handler))
        .route("/sermons/archive", get(sermons::sermons_archive_handler))
        .route("/events", get(events::events_handler))
        .route("/events/upcoming", get(events::upcoming_events_handler))
        .route("/events/:id", get(events::event_detail_handler))
        .route("/bulletins", get(bulletins::bulletins_handler))
        .route("/bulletins/:id", get(bulletins::bulletin_detail_handler))
        .route("/contact", get(contact::contact_handler))
        .route("/contact", post(contact::contact_form_handler))
        .route("/debug/api", get(|| async {
            use crate::services::ApiService;
            let api = ApiService::new();
            let (config, events, bulletins) = tokio::join!(
                api.get_config(),
                api.get_events(None), // Get all events
                api.get_bulletins()
            );
            format!("Config: {:?}\nEvents: {:?}\nBulletins: {} items", 
                config.is_ok(), 
                match &events {
                    Ok(events) => format!("OK - {} items: {:?}", events.len(), events.iter().map(|e| &e.title).collect::<Vec<_>>()),
                    Err(e) => format!("ERROR: {}", e)
                },
                bulletins.as_ref().map(|b| b.len()).unwrap_or(0)
            )
        }))
        .nest_service("/css", ServeDir::new("css").precompressed_gzip())
        .nest_service("/js", ServeDir::new("js").precompressed_gzip())
        .nest_service("/images", ServeDir::new("images"))
        .layer(
            CorsLayer::new()
                .allow_origin(tower_http::cors::Any)
                .allow_methods([axum::http::Method::GET, axum::http::Method::POST])
                .allow_headers(tower_http::cors::Any)
        );

    let addr = SocketAddr::from(([0, 0, 0, 0], 3001));
    info!("Server running on {}", addr);
    
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
