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

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

#[actix_web::delete("/area/delete/{id}")]
pub async fn delete(
    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 Area::read_by_id(pool.get_ref(), path.id).await?.is_none() {
        return Ok(HttpResponse::NotFound().finish());
    };

    Area::delete(pool.get_ref(), path.id).await?;

    return Ok(HttpResponse::Ok().finish());
}
