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

#[derive(thiserror::Error, Debug)]
enum MemberExtractorErr {
    #[error("Member {0:?} does not belong to family {1:?}!")]
    MemberNotInFamily(MemberID, FamilyID),
}

#[derive(Debug)]
pub struct FamilyAndMemberInPath(Membership, Member);

impl FamilyAndMemberInPath {
    async fn load_member_from_path(
        family: FamilyInPath,
        member_id: MemberID,
    ) -> anyhow::Result<Self> {
        let member = members_service::get_by_id(member_id).await?;
        if member.family_id() != family.family_id() {
            return Err(
                MemberExtractorErr::MemberNotInFamily(member.id(), family.family_id()).into(),
            );
        }

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

impl Deref for FamilyAndMemberInPath {
    type Target = Member;

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

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

    pub fn to_member(self) -> Member {
        self.1
    }
}

#[derive(Deserialize)]
struct MemberIDInPath {
    member_id: MemberID,
}

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

            FamilyAndMemberInPath::load_member_from_path(family, member_id)
                .await
                .map_err(|e| {
                    log::error!("Failed to extract member ID from URL! {e}");
                    actix_web::error::ErrorNotFound("Could not fetch member information!")
                })
        })
    }
}
