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

use crate::{
    endpoints::vehicle_assignment::PlanVehiclesPartialTemplate,
    models::{Event, Role, User, VehicleAssignement},
    utils::{event_planning_template::generate_vehicles_assigned_and_available, ApplicationError},
};

#[derive(Deserialize)]
struct VehicleAssignmentDeleteQuery {
    vehicle: i32,
    event: i32,
}

#[actix_web::delete("/vehicleassignments/delete")]
pub async fn delete(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    query: web::Query<VehicleAssignmentDeleteQuery>,
) -> Result<impl Responder, ApplicationError> {
    let Some(event) = Event::read_by_id_including_location(pool.get_ref(), query.event).await?
    else {
        return Ok(HttpResponse::NotFound().finish());
    };

    let user_is_admin_or_area_manager_of_event_area = user.role == Role::Admin
        || (user.role == Role::AreaManager
            && user.area_id == event.location.as_ref().unwrap().area_id);

    if !user_is_admin_or_area_manager_of_event_area {
        return Err(ApplicationError::Unauthorized);
    }

    let Some(vehicle_assignment) =
        VehicleAssignement::read(pool.get_ref(), event.id, query.vehicle).await?
    else {
        return Ok(HttpResponse::NotFound().finish());
    };

    VehicleAssignement::delete(
        pool.get_ref(),
        vehicle_assignment.event_id,
        vehicle_assignment.vehicle_id,
    )
    .await?;

    let (vehicles_assigned, vehicles_available) =
        generate_vehicles_assigned_and_available(pool.get_ref(), &event).await?;
    let template = PlanVehiclesPartialTemplate {
        event,
        vehicles_assigned,
        vehicles_available,
    };

    Ok(HttpResponse::Ok().body(template.render()?))
}
