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

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

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

    let Some(_) = Vehicle::read(pool.get_ref(), path.id).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

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

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