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

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

#[derive(Template)]
#[template(path = "events/new.html")]
pub struct NewEventTemplate {
    user: User,
    date: NaiveDate,
    locations: Vec<Location>,
}

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

    let locations = if user.role == Role::Admin {
        Location::read_all_including_area(pool.get_ref()).await?
    } else {
        Location::read_by_area(pool.get_ref(), user.area_id).await?
    };

    let template = NewEventTemplate {
        user: user.into_inner(),
        date: query.date,
        locations,
    };

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