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

#[derive(thiserror::Error, Debug)]
enum CoupleExtractorErr {
    #[error("Couple {0:?} does not belong to family {1:?}!")]
    CoupleNotInFamily(CoupleID, FamilyID),
}

#[derive(Debug)]
pub struct FamilyAndCoupleInPath(Membership, Couple);

impl FamilyAndCoupleInPath {
    async fn load_couple_from_path(
        family: FamilyInPath,
        couple_id: CoupleID,
    ) -> anyhow::Result<Self> {
        let couple = couples_service::get_by_id(couple_id).await?;
        if couple.family_id() != family.family_id() {
            return Err(
                CoupleExtractorErr::CoupleNotInFamily(couple.id(), family.family_id()).into(),
            );
        }

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

impl Deref for FamilyAndCoupleInPath {
    type Target = Couple;

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

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

    pub fn to_couple(self) -> Couple {
        self.1
    }
}

#[derive(Deserialize)]
struct CoupleIDInPath {
    couple_id: CoupleID,
}

impl FromRequest for FamilyAndCoupleInPath {
    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 couple_id =
                actix_web::web::Path::<CoupleIDInPath>::from_request(&req, &mut Payload::None)
                    .await?
                    .couple_id;

            FamilyAndCoupleInPath::load_couple_from_path(family, couple_id)
                .await
                .map_err(|e| {
                    log::error!("Failed to extract couple ID from URL! {e}");
                    actix_web::error::ErrorNotFound("Could not fetch couple information!")
                })
        })
    }
}
