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

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

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

    Availabillity::delete(pool.get_ref(), availabillity.id).await?;

    Ok(HttpResponse::Ok().finish())
}
