/*-
 * ~~~~~~licensing~~~~~~
 * permission-impl
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.core.permission.interceptor;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.ws.rs.ForbiddenException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.Headers;
import org.osgi.framework.FrameworkUtil;

import ru.entaxy.esb.system.auth.basic.jpa.api.BasicAuthService;
import ru.entaxy.esb.system.auth.basic.jpa.api.entity.BasicAuthAccount;
import ru.entaxy.esb.system.core.permission.common.PermissionConstants;
import ru.entaxy.esb.system.core.permission.jpa.PermissionService;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;

public class ServiceInterceptor extends AbstractPhaseInterceptor<Message> {

    private static final Log LOG = LogFactory.getLog(ServiceInterceptor.class);
    private static final String APACHE_CXF_MESSAGE_MESSAGE_PATH_INFO = "org.apache.cxf.message.Message.PATH_INFO";
    private static final String HEADER_USER_LOGIN = "X-ForwardedUser";
    private static final String CXF = "/cxf/";

    private PermissionService permissionService;
    private BasicAuthService basicAuthService;

    public ServiceInterceptor() {
        super(Phase.RECEIVE);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);
        String serviceName = message.get(APACHE_CXF_MESSAGE_MESSAGE_PATH_INFO).toString();
        if (serviceName.contains(CXF)) {
            serviceName = serviceName.replace(CXF, "");
        } else {
            int firstSlashIndex = serviceName.indexOf("/") + 1;
            serviceName = serviceName.substring(firstSlashIndex, serviceName.indexOf("/", firstSlashIndex));
        }

        Optional<String> login = Optional.ofNullable(headers.get(HEADER_USER_LOGIN))
                .orElse(Collections.emptyList())
                .stream().findFirst();

        Optional<BasicAuthAccount> basicAuthAccount = Optional.empty();
        if (login.isPresent()) {
            basicAuthAccount = getBasicAuthService().get(login.get());
        }

        LOG.trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>ServiceInterceptor" +
                " <<< serviceName " + serviceName +
                " <<< login " + login);
        if (!login.isPresent() || !basicAuthAccount.isPresent() ||
                !getPermissionService().existByAllParameters(basicAuthAccount.get().getId(),
                        PermissionConstants.TYPE_ACCOUNT,
                        serviceName, PermissionConstants.TYPE_SERVICE, null)) {
            throw new ForbiddenException();
        }
    }

    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    public PermissionService getPermissionService() {
        if (permissionService == null) {
            permissionService = (PermissionService) OSGIUtils.getService(
                    FrameworkUtil.getBundle(ServiceInterceptor.class).getBundleContext(),
                    PermissionService.class);
        }
        return permissionService;
    }

    public void setBasicAuthService(BasicAuthService basicAuthService) {
        this.basicAuthService = basicAuthService;
    }

    public BasicAuthService getBasicAuthService() {
        if (basicAuthService == null) {
            basicAuthService = (BasicAuthService) OSGIUtils.getService(
                    FrameworkUtil.getBundle(ServiceInterceptor.class).getBundleContext(),
                    BasicAuthService.class);
        }
        return basicAuthService;
    }

}
