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

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

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

    let Some(location) = Location::read_by_id(pool.get_ref(), path.id).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

    if user.role == Role::AreaManager && location.area_id != user.area_id {
        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: Some(location),
    };

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