#![cfg(feature = "web")]

use crate::{auth::UserContext, error::AppError};
use actix_service::{forward_ready, Service, Transform};
use actix_web::{
    dev::{ServiceRequest, ServiceResponse},
    Error, HttpMessage,
};
use futures_util::future::{ready, LocalBoxFuture, Ready};
use std::rc::Rc;

/// Async identity-resolution strategy — the single extension point shared by every service.
///
/// The resolver takes **ownership** of the request so it can:
/// - perform I/O (verify a signature, read a session from Redis, query a DB), and
/// - enrich request extensions (e.g. insert a `TenantContext`) before handlers run,
///
/// then returns the request back together with the resolved [`UserContext`] (or `None` for an
/// anonymous request). A purely synchronous resolver (e.g. signed-header parsing with no I/O)
/// simply returns an already-ready future — there is no cost beyond a single boxed future, so
/// the same primitive serves both stateless and stateful services.
pub type UserContextResolver = Rc<
    dyn Fn(
        ServiceRequest,
    )
        -> LocalBoxFuture<'static, (ServiceRequest, Result<Option<UserContext>, AppError>)>,
>;

/// UserContext middleware:
/// - resolver `Ok(Some(ctx))` → inserts `ctx` into extensions
/// - resolver `Ok(None)` with `required = true` → 401
/// - resolver `Err(e)` → `e` rendered via its `ResponseError` impl
pub struct UserContextMiddleware {
    resolver: UserContextResolver,
    required: bool,
}

impl UserContextMiddleware {
    pub fn new<F>(resolver: F) -> Self
    where
        F: Fn(
                ServiceRequest,
            )
                -> LocalBoxFuture<'static, (ServiceRequest, Result<Option<UserContext>, AppError>)>
            + 'static,
    {
        Self {
            resolver: Rc::new(resolver),
            required: false,
        }
    }

    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }
}

impl<S, B> Transform<S, ServiceRequest> for UserContextMiddleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = UserContextMiddlewareService<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(UserContextMiddlewareService {
            service: Rc::new(service),
            resolver: self.resolver.clone(),
            required: self.required,
        }))
    }
}

pub struct UserContextMiddlewareService<S> {
    service: Rc<S>,
    resolver: UserContextResolver,
    required: bool,
}

impl<S, B> Service<ServiceRequest> for UserContextMiddlewareService<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let srv = self.service.clone();
        let resolver = self.resolver.clone();
        let required = self.required;

        Box::pin(async move {
            let (mut req, outcome) = (resolver)(req).await;

            match outcome {
                Ok(Some(ctx)) => {
                    req.extensions_mut().insert(ctx);
                }
                Ok(None) => {
                    if required {
                        return Err(AppError::Unauthorized {
                            message: "Missing user context".to_string(),
                        }
                        .into());
                    }
                }
                Err(app_err) => {
                    return Err(app_err.into());
                }
            }

            srv.call(req).await
        })
    }
}
