//! Public landing page.

use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use serde_json::json;

use crate::{
    controllers::i18n::current_lang, controllers::shop, shared::currency, shared::guard,
};

#[debug_handler]
async fn index(
    jar: CookieJar,
    ViewEngine(v): ViewEngine<TeraView>,
    State(ctx): State<AppContext>,
) -> Result<Response> {
    let user = guard::current_user(&ctx, &jar).await;
    let cur = currency::resolve(&ctx, &jar).await;
    let products = shop::featured_products(&ctx, user.as_ref(), 8, &cur).await?;
    let c = guard::chrome_from(&ctx, user.as_ref());

    format::view(
        &v,
        "home/index.html",
        json!({
            "products": products,
            "logged_in_admin": c.logged_in_admin,
            "logged_in_customer": c.logged_in_customer,
            "customer_name": c.customer_name,
            "customer_account_type": c.customer_account_type,
            "customer_avatar": c.customer_avatar,
            "currency_symbol": cur.symbol,
            "lang": current_lang(&jar),
            // The header search bar only appears on the landing page.
            "on_home": true,
        }),
    )
}

pub fn routes() -> Routes {
    Routes::new().add("/", get(index))
}
