use actix_web::{web, HttpRequest, HttpResponse};

use crate::pages::templates::INDEX;
use crate::pages::{insert_security_headers, request_to_jar, CommonAuthInfo};
use crate::WebData;

#[derive(serde_derive::Serialize)]
struct PageData<'a> {
    pub common_auth_info: CommonAuthInfo<'a>,
    pub version: &'a str,
}

pub async fn index(request: HttpRequest, data: web::Data<WebData<'_>>) -> HttpResponse {
    let jar = request_to_jar(request);

    let user = jar
        .private(&data.cookies_key)
        .get("auth")
        .map(|x| x.value().to_string());

    let body = match data.handlebars.render(
        INDEX,
        &PageData {
            common_auth_info: CommonAuthInfo {
                user: user.map(Into::into),
            },
            version: &data.freeorion_version,
        },
    ) {
        Ok(b) => b,
        Err(e) => {
            log::error!("Render index error: {}", e);
            return HttpResponse::ServiceUnavailable().body(actix_web::body::None::new());
        }
    };
    insert_security_headers(HttpResponse::Ok()).body(body)
}