use crate::extractors::auth_extractor::AuthExtractor;
use crate::models::inbox::{InboxEntry, InboxEntryID};
use crate::services::inbox_service;
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use serde::Deserialize;

#[derive(Deserialize)]
struct InboxEntryIdInPath {
    inbox_id: InboxEntryID,
}

#[derive(thiserror::Error, Debug)]
enum InboxEntryExtractorError {
    #[error("Current user does not own the entry!")]
    UserDoesNotOwnInboxEntry,
}

pub struct InboxEntryInPath(InboxEntry);

impl InboxEntryInPath {
    pub async fn load_inbox_entry_from_path(
        auth: &AuthExtractor,
        id: InboxEntryID,
    ) -> anyhow::Result<Self> {
        let entry = inbox_service::get_by_id(id).await?;

        if entry.user_id() != auth.user_id() {
            return Err(InboxEntryExtractorError::UserDoesNotOwnInboxEntry.into());
        }

        Ok(Self(entry))
    }
}

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

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

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