use actix_web::{web, HttpResponse, Responder};
use rinja::Template;
use sqlx::PgPool;

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

#[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>
) -> Result<impl Responder, ApplicationError> {
    if user.role != Role::Admin && user.role != Role::AreaManager {
        return Err(ApplicationError::Unauthorized);
    }

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

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

    Ok(HttpResponse::Ok().body(template.render()?))
}
