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

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

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

    let mut areas = None;

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

    let template = LocationTemplate {
        user: user.into_inner(),
        areas,
        location: None,
    };

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