use axum::{
    extract::State,
    response::{IntoResponse, Redirect, Response},
    routing::get,
    Router,
};
use tower_cookies::Cookies;

use crate::render::render;
use crate::routes::auth::is_authenticated;
use crate::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/", get(home))
        .route("/changelog", get(changelog))
}

pub async fn home(State(state): State<AppState>, cookies: Cookies) -> Response {
    let authed = is_authenticated(&cookies, &state);
    if authed {
        return Redirect::to("/properties").into_response();
    }
    let totals: (i64, i64, Option<i64>) = sqlx::query_as(
        "SELECT \
           (SELECT COUNT(*) FROM checks), \
           (SELECT COUNT(*) FROM properties), \
           (SELECT MIN(created_at) FROM checks)",
    )
    .fetch_one(&state.pool)
    .await
    .unwrap_or((0, 0, None));

    let first = totals.2.and_then(|ms| {
        chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ms)
            .map(|d| d.format("%b %-d, %Y").to_string())
    });

    let extra = minijinja::context! {
        page => minijinja::context! {
            title => "Home",
            description => "Self-hosted uptime monitoring with status pages.",
        },
        title => "Home",
        description => "Self-hosted uptime monitoring with status pages.",
        total_statuses => totals.0,
        total_properties => totals.1,
        first_status_created_at => first,
    };
    render(&state, "pages/home.html", "/", authed, extra)
}

pub async fn changelog(State(state): State<AppState>, cookies: Cookies) -> Response {
    let authed = is_authenticated(&cookies, &state);
    let extra = minijinja::context! {
        page => minijinja::context! {
            title => "Changelog",
            description => "An ongoing changelog and upcoming list of features for Status.",
        },
        title => "Changelog",
        description => "An ongoing changelog and upcoming list of features for Status.",
    };
    render(&state, "pages/changelog.html", "/changelog", authed, extra)
}
