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

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

#[actix_web::delete("/locations/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::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);
    }

    Location::delete(pool.get_ref(), location.id).await?;

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