use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use sqlx::PgPool;

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

use super::AreaForm;

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

    if let Some(area) = Area::read_by_id(pool.get_ref(), path.id).await? {
        if area.name != form.name {
            Area::update(pool.get_ref(), path.id, &form.name).await?;
        }

        return Ok(HttpResponse::Found()
            .insert_header((LOCATION, "/locations"))
            .insert_header(("HX-LOCATION", "/locations"))
            .finish());
    } else {
        return Ok(HttpResponse::NotFound().finish());
    }
}
