use crate::extractors::family_extractor::FamilyInPath;
use crate::models::{
    AccommodationReservationCalendar, AccommodationReservationCalendarID, FamilyID, Membership,
};
use crate::services::accommodations_reservations_calendars_service;
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use serde::Deserialize;
use std::ops::Deref;

#[derive(thiserror::Error, Debug)]
enum AccommodationCalendarExtractorErr {
    #[error("Calendar {0:?} does not belong to user or family {1:?}!")]
    CalendarNotOfUserOrFamily(AccommodationReservationCalendarID, FamilyID),
}

#[derive(Debug)]
pub struct FamilyAndAccommodationReservationCalendarInPath(
    Membership,
    AccommodationReservationCalendar,
);

impl FamilyAndAccommodationReservationCalendarInPath {
    async fn load_calendar_from_path(
        family: FamilyInPath,
        calendar_id: AccommodationReservationCalendarID,
    ) -> anyhow::Result<Self> {
        let accommodation =
            accommodations_reservations_calendars_service::get_by_id(calendar_id).await?;
        if accommodation.family_id() != family.family_id()
            || accommodation.user_id() != family.user_id()
        {
            return Err(
                AccommodationCalendarExtractorErr::CalendarNotOfUserOrFamily(
                    accommodation.id(),
                    family.family_id(),
                )
                .into(),
            );
        }

        Ok(Self(family.into(), accommodation))
    }
}

impl Deref for FamilyAndAccommodationReservationCalendarInPath {
    type Target = AccommodationReservationCalendar;

    fn deref(&self) -> &Self::Target {
        &self.1
    }
}

impl FamilyAndAccommodationReservationCalendarInPath {
    pub fn membership(&self) -> &Membership {
        &self.0
    }

    pub fn to_reservation(self) -> AccommodationReservationCalendar {
        self.1
    }
}

#[derive(Deserialize)]
struct AccommodationIDInPath {
    cal_id: AccommodationReservationCalendarID,
}

impl FromRequest for FamilyAndAccommodationReservationCalendarInPath {
    type Error = actix_web::Error;
    type Future = futures_util::future::LocalBoxFuture<'static, Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        let req = req.clone();
        Box::pin(async move {
            let family = FamilyInPath::extract(&req).await?;

            let accommodation_id = actix_web::web::Path::<AccommodationIDInPath>::from_request(
                &req,
                &mut Payload::None,
            )
            .await?
            .cal_id;

            Self::load_calendar_from_path(family, accommodation_id)
                .await
                .map_err(|e| {
                    log::error!("Failed to extract calendar ID from URL! {e}");
                    actix_web::error::ErrorNotFound("Could not fetch calendar information!")
                })
        })
    }
}
