use actix_web::{web, HttpResponse, Responder};
use askama::Template;
use askama_actix::TemplateToResponse;
use sqlx::PgPool;

use crate::models::{Area, User, Role};

#[derive(Template)]
#[template(path = "export/availability.html")]
struct AvailabilityExportTemplate {
    user: User,
    areas: Option<Vec<Area>>
}

#[actix_web::get("/export/availability")]
pub async fn get(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>
) -> impl Responder {
    if user.role != Role::Admin && user.role != Role::AreaManager {
        return HttpResponse::Unauthorized().finish();
    }

    let areas = if user.role == Role::Admin {
        Some(Area::read_all(pool.get_ref()).await.unwrap())
    } else {
        None
    };

    let template = AvailabilityExportTemplate {
        user: user.into_inner(),
        areas
    };

    return template.to_response();
}
