use crate::extractors::auth_extractor::AuthExtractor;
use crate::models::files::{File, FileID};
use crate::services::files_service;
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use serde::Deserialize;

#[derive(Deserialize)]
struct FileIdInPath {
    file_id: FileID,
}

#[derive(thiserror::Error, Debug)]
enum FileIdExtractorError {
    #[error("Current user does not own the file!")]
    UserDoesNotOwnFile,
}

pub struct FileIdExtractor(File);

impl FileIdExtractor {
    pub async fn load_file_from_path(auth: &AuthExtractor, id: FileID) -> anyhow::Result<Self> {
        let file = files_service::get_file_with_id(id)?;

        if file.user_id() != auth.user_id() {
            return Err(FileIdExtractorError::UserDoesNotOwnFile.into());
        }

        Ok(Self(file))
    }
}

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

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

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