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

use crate::{
    endpoints::IdPath,
    filters,
    models::{Availabillity, AvailabillityAssignmentState, Event, Function, Role, User},
    utils::{
        event_planning_template::{
            generate_availabillity_assignment_list, generate_status_whether_staff_is_required,
        },
        ApplicationError,
    },
};

#[derive(Template)]
#[template(path = "events/plan.html")]
pub struct PlanEventTemplate {
    user: User,
    event: Event,
    availabillities: Vec<(Availabillity, AvailabillityAssignmentState)>,
    further_posten_required: bool,
    further_fuehrungsassistent_required: bool,
    further_wachhabender_required: bool,
}

#[actix_web::get("/events/{id}/plan")]
pub async fn get(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    path: web::Path<IdPath>,
) -> Result<impl Responder, ApplicationError> {
    if user.role != Role::Admin && user.role != Role::AreaManager {
        return Err(ApplicationError::Unauthorized);
    }

    let Some(event) = Event::read_by_id_including_location(pool.get_ref(), path.id).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

    if user.role != Role::Admin && user.area_id != event.location.as_ref().unwrap().area_id {
        return Err(ApplicationError::Unauthorized);
    }

    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 = PlanEventTemplate {
        user: user.into_inner(),
        event,
        availabillities,
        further_posten_required,
        further_fuehrungsassistent_required,
        further_wachhabender_required,
    };

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