use crate::html::{api, blog, AppState};
use axum::{
    http::StatusCode,
    response::{IntoResponse, Redirect},
    routing::{get, Router},
    Extension,
};
use sqlx::PgPool;
use tower_http::services::ServeDir;

use super::{garden, get_page};

pub fn get_router(pool: PgPool) -> Router {
    let assets_path = std::env::current_dir().unwrap();
    let state = AppState { db: pool };
    Router::new()
        .nest("/api", api::get_router())
        .nest("/blog", blog::get_router())
        .nest("/garden", garden::get_router())
        .nest_service(
            "/assets",
            ServeDir::new(format!("{}/assets", assets_path.to_str().unwrap())),
        )
        .route("/", get(home))
        .route("/now", get(now))
        .route("/about", get(about))
        .route("/contact", get(contact))
        .route("/uses", get(uses))
        .route(
            "/robots.txt",
            get(|| async { Redirect::permanent("/assets/robots.txt") }),
        )
        .layer(Extension(state))
}

async fn home(state: Extension<AppState>) -> Result<impl IntoResponse, StatusCode> {
    get_page(&state.db, "home").await
}

async fn now(state: Extension<AppState>) -> Result<impl IntoResponse, StatusCode> {
    get_page(&state.db, "now").await
}

async fn about(state: Extension<AppState>) -> Result<impl IntoResponse, StatusCode> {
    get_page(&state.db, "about").await
}

async fn contact(state: Extension<AppState>) -> Result<impl IntoResponse, StatusCode> {
    get_page(&state.db, "contact").await
}

async fn uses(state: Extension<AppState>) -> Result<impl IntoResponse, StatusCode> {
    get_page(&state.db, "uses").await
}
