package ru.yandex.webmaster3.api.user.filter;

import lombok.extern.slf4j.Slf4j;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.rest.request.ApiRequest;
import ru.yandex.webmaster3.api.http.rest.request.ApiRequestFilter;
import ru.yandex.webmaster3.api.http.rest.response.ApiResponse;
import ru.yandex.webmaster3.api.http.rest.response.errors.ApiErrorCode;
import ru.yandex.webmaster3.api.http.rest.response.errors.ApiErrorResponse;
import ru.yandex.webmaster3.storage.abt.AbtService;
import ru.yandex.webmaster3.storage.abt.model.Experiment;

/**
 * @author leonidrom
 */
@Slf4j
public class UserExperimentFilter <Req extends ApiRequest<?> & ApiUserIdAwareRequest>
        implements ApiRequestFilter<Req, UserExperimentFilter.UserNotInExperimentError> {

    private final AbtService abtService;
    private final Experiment[] allowedExperiments;

    public UserExperimentFilter(AbtService abtService, Experiment[] allowedExperiments) {
        this.abtService = abtService;
        this.allowedExperiments = allowedExperiments;
    }

    @Override
    public UserNotInExperimentError applyFilter(Req req) {
        if (!abtService.isOneOfExperiments(req.getAuthorizedUserId(), allowedExperiments)) {
            return new UserNotInExperimentError.AccessForbidden();
        }

        return null;
    }

    public interface UserNotInExperimentError extends ApiErrorResponse<UserNotInExperimentError.Code> {
        enum Code implements ApiErrorCode {
            ACCESS_FORBIDDEN,
            ;
        }

        @Description("Действие недоступно, у пользователя нет доступа")
        class AccessForbidden extends ApiResponse.Forbidden403<UserNotInExperimentError.Code> implements UserNotInExperimentError {
            public AccessForbidden() {
                super(Code.ACCESS_FORBIDDEN, "Access to this resource is not allowed for user");
            }
        }
    }
}
