use crate::extractors::auth_extractor::AuthExtractor;
use crate::models::accounts::Account;
use crate::models::movements::{Movement, MovementID};
use crate::services::{accounts_service, movements_service};
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use serde::Deserialize;

#[derive(Deserialize)]
struct MovementIdInPath {
    movement_id: MovementID,
}

#[derive(thiserror::Error, Debug)]
enum AccountExtractorError {
    #[error("Current user does not own the account associated to this movement!")]
    UserDoesNotOwnAccount,
}

pub struct MovementInPath(Account, Movement);

impl MovementInPath {
    async fn load_movement_from_path(auth: &AuthExtractor, id: MovementID) -> anyhow::Result<Self> {
        let movement = movements_service::get_by_id(id).await?;

        let account = accounts_service::get_by_id(movement.account_id()).await?;

        if account.user_id() != auth.user_id() {
            return Err(AccountExtractorError::UserDoesNotOwnAccount.into());
        }

        Ok(Self(account, movement))
    }

    pub fn account(&self) -> &Account {
        &self.0
    }
    pub fn movement(&self) -> &Movement {
        &self.1
    }
}

impl FromRequest for MovementInPath {
    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 auth = AuthExtractor::extract(&req).await?;

            let account_id =
                actix_web::web::Path::<MovementIdInPath>::from_request(&req, &mut Payload::None)
                    .await?
                    .movement_id;

            Self::load_movement_from_path(&auth, account_id)
                .await
                .map_err(|e| {
                    log::error!("Failed to extract movement ID from URL! {e}");
                    actix_web::error::ErrorNotFound("Could not fetch movement information!")
                })
        })
    }
}

impl AsRef<Movement> for MovementInPath {
    fn as_ref(&self) -> &Movement {
        &self.1
    }
}
