use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use sqlx::PgPool;

use crate::{
    endpoints::{availability::post_new::AvailabillityForm, IdPath},
    models::{Availabillity, User},
    utils::{self, ApplicationError},
};

#[actix_web::post("/availabillity/edit/{id}")]
pub async fn post(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    path: web::Path<IdPath>,
    form: web::Form<AvailabillityForm>,
) -> Result<impl Responder, ApplicationError> {
    let Some(availabillity) = Availabillity::read_by_id(pool.get_ref(), path.id).await? else {
        return Ok(HttpResponse::NotFound().finish());
    };

    if availabillity.user_id != user.id {
        return Err(ApplicationError::Unauthorized);
    }

    if availabillity.start_time != form.from
        || availabillity.end_time != form.till
        || availabillity.comment != form.comment
    {
        Availabillity::update(
            pool.get_ref(),
            availabillity.id,
            form.from,
            form.till,
            form.comment.as_ref(),
        )
        .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())
}
