use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use chrono::{NaiveDate, NaiveTime};
use serde::Deserialize;
use sqlx::PgPool;

use crate::{models::{Event, Role, User}, utils::{self, ApplicationError}};

#[derive(Deserialize)]
pub struct NewEventForm {
    name: String,
    date: NaiveDate,
    from: NaiveTime,
    till: NaiveTime,
    location: i32,
    voluntarywachhabender: Option<bool>,
    amount: i16,
    clothing: String,
    note: Option<String>
}

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

    Event::create(
        pool.get_ref(),
        &form.date,
        &form.from,
        &form.till,
        &form.name,
        form.location,
        form.voluntarywachhabender.is_some() && form.voluntarywachhabender.unwrap(),
        form.amount,
        &form.clothing,
        form.note.as_ref()
    )
    .await?;

    let url = utils::get_return_url_for_date(&form.date);
    println!("redirecto to {url}");
    Ok(HttpResponse::Found()
        .insert_header((LOCATION, url.clone()))
        .insert_header(("HX-LOCATION", url))
        .finish())
}
