use askama::Template;
use askama_web::WebTemplate;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use kube::{Api, api::ListParams};

use crate::auth_guard::AuthUser;
use crate::flash;
use crate::k8s::SojuBouncer;
use crate::page::PageContext;
use crate::state::AppState;

#[derive(Template, WebTemplate)]
#[template(path = "dashboard.html")]
pub struct DashboardTemplate {
    pub page: PageContext,
    pub has_bouncer: bool,
    pub is_pro: bool,
    pub plan: String,
}

pub async fn index(
    State(state): State<AppState>,
    headers: HeaderMap,
    AuthUser(user): AuthUser,
) -> impl IntoResponse {
    let bouncers: Api<SojuBouncer> = Api::namespaced(state.kube.clone(), &state.namespace);
    let lp = ListParams::default().labels(&format!("irc.now/owner={}", user.sub));
    let has_bouncer = bouncers
        .list(&lp)
        .await
        .map(|list| !list.items.is_empty())
        .unwrap_or(false);

    let plan = user.plan.unwrap_or_else(|| "free".to_string());
    let is_pro = plan == "pro";

    let page = PageContext::from_request(&headers, &state.announcement);
    let clear = page.flash.is_some();

    let template = DashboardTemplate {
        page,
        has_bouncer,
        is_pro,
        plan,
    };

    if clear {
        (axum::response::AppendHeaders([flash::clear_flash()]), template).into_response()
    } else {
        template.into_response()
    }
}
