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

#[derive(Deserialize)]
struct AccountIdInPath {
    account_id: AccountID,
}

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

pub struct AccountInPath(Account);

impl AccountInPath {
    pub async fn load_account_from_path(
        auth: &AuthExtractor,
        id: AccountID,
    ) -> anyhow::Result<Self> {
        let account = accounts_service::get_by_id(id).await?;

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

        Ok(Self(account))
    }
}

impl FromRequest for AccountInPath {
    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::<AccountIdInPath>::from_request(&req, &mut Payload::None)
                    .await?
                    .account_id;

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

impl AsRef<Account> for AccountInPath {
    fn as_ref(&self) -> &Account {
        &self.0
    }
}
