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

use crate::{
    endpoints::{area::NewOrEditAreaTemplate, IdPath},
    models::{Area, Role, User},
    utils::ApplicationError,
};

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

    if let Some(area_in_db) = Area::read_by_id(pool.get_ref(), path.id).await? {
        let template = NewOrEditAreaTemplate {
            user: user.into_inner(),
            area: Some(area_in_db),
        };

        return Ok(HttpResponse::Ok().body(template.render()?))
    } else {
        return Ok(HttpResponse::NotFound().finish());
    }
}
