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

use crate::{
    endpoints::{availability::NewOrEditAvailabilityTemplate, IdPath},
    models::{Availabillity, User},
    utils::ApplicationError,
};

#[derive(Deserialize)]
struct EditAvailabilityQuery {
    #[serde(rename(deserialize = "wholeday"))]
    whole_day: Option<bool>,
}

#[actix_web::get("/availabillity/edit/{id}")]
pub async fn get(
    user: web::ReqData<User>,
    pool: web::Data<PgPool>,
    path: web::Path<IdPath>,
    query: web::Query<EditAvailabilityQuery>,
) -> 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);
    }

    let start_time = availabillity
        .start_time
        .and_then(|d| Some(d.format("%R").to_string()));

    let end_time = availabillity
        .end_time
        .and_then(|d| Some(d.format("%R").to_string()));

    let has_time = availabillity.start_time.is_some() && availabillity.end_time.is_some();

    let template = NewOrEditAvailabilityTemplate {
        user: user.into_inner(),
        date: availabillity.date,
        whole_day: query.whole_day.unwrap_or(!has_time),
        id: Some(path.id),
        start_time: start_time.as_deref(),
        end_time: end_time.as_deref(),
        comment: availabillity.comment.as_deref(),
    };

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