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

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

#[derive(Deserialize)]
pub struct AvailabillityForm {
    pub date: NaiveDate,
    pub from: Option<NaiveTime>,
    pub till: Option<NaiveTime>,
    pub comment: Option<String>,
}

#[actix_web::post("/availabillity/new")]
pub async fn post(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    form: web::Form<AvailabillityForm>,
) -> Result<impl Responder, ApplicationError> {
    Availabillity::create(
        pool.get_ref(),
        user.id,
        form.date,
        form.from,
        form.till,
        form.comment.clone(),
    )
    .await?;

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