use cfg_if::cfg_if;
cfg_if! { if #[cfg(feature = "ssr")] {

    use std::future::{Ready, ready};
    use actix_session::SessionExt;
    use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
    use actix_web::Error;
    use actix_web::HttpResponse;
    use actix_web::body::EitherBody;
    use futures_util::future::LocalBoxFuture;
    use actix_web::http::header::LOCATION;
    use crate::backend::data::User;

    pub struct Authentication;

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

        fn new_transform(&self, service: S) -> Self::Future {
            ready(Ok(AuthenticationMiddleware { service }))
        }
    }
    pub struct AuthenticationMiddleware<S> {
        service: S,
    }

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

        forward_ready!(service);

        fn call(&self, req: ServiceRequest) -> Self::Future {
            let session = req.get_session();
            let authenticate_pass = !req.path().starts_with("/admin") ||
                session.get::<User>("user").unwrap_or(None).is_some();

            if authenticate_pass {
                let res = self.service.call(req);

                Box::pin(async move {
                    res.await.map(ServiceResponse::map_into_left_body)
                })
            } else {
                let (request, _pl) = req.into_parts();

                let response = HttpResponse::Found()
                    .insert_header((LOCATION, "/login"))
                    .finish()
                    .map_into_right_body();

                Box::pin(async { Ok(ServiceResponse::new(request, response)) })
            }
        }
    }
}}
