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

use crate::{
    endpoints::assignment::PlanEventPersonalTablePartialTemplate,
    models::{Assignment, Event, Role, User},
    utils::{
        event_planning_template::{
            generate_availabillity_assignment_list, generate_status_whether_staff_is_required,
        },
        ApplicationError,
    },
};

#[derive(Deserialize)]
struct AssignmentDeleteQuery {
    availabillity: i32,
    event: i32,
}

#[actix_web::delete("/assignments/delete")]
pub async fn delete(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    query: web::Query<AssignmentDeleteQuery>,
) -> 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(assignment) = Assignment::read(pool.get_ref(), event.id, query.availabillity).await?
    else {
        return Ok(HttpResponse::NotFound().finish());
    };

    Assignment::delete(pool.get_ref(), event.id, assignment.availabillity_id).await?;

    let availabillities = generate_availabillity_assignment_list(pool.get_ref(), &event).await?;
    let (
        further_posten_required,
        further_fuehrungsassistent_required,
        further_wachhabender_required,
    ) = generate_status_whether_staff_is_required(pool.get_ref(), &event).await?;

    let template = PlanEventPersonalTablePartialTemplate {
        event,
        availabillities,
        further_posten_required,
        further_fuehrungsassistent_required,
        further_wachhabender_required,
    };

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