/*-
 * ~~~~~~licensing~~~~~~
 * basic-auth-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.auth.basic.interceptor;

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 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.common.util.SystemHeadersConstants;
import ru.entaxy.esb.system.jpa.SystemService;
import ru.entaxy.esb.system.jpa.entity.System;

import javax.ws.rs.ForbiddenException;
import java.util.*;

public class SystemInterceptor extends AbstractPhaseInterceptor<Message> {

    private static final Log LOG = LogFactory.getLog(SystemInterceptor.class);

    private BasicAuthService basicAuthService;
    private SystemService systemService;

    public SystemInterceptor() {
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        Map<String, List<String>> headers = Headers.getSetProtocolHeaders(message);

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

        Optional<String> isDisplayServiceSchema = Optional.ofNullable(headers.get(SystemHeadersConstants.HEADER_IS_DISPLAY_SERVICE_SERVICE)).
                orElse(Collections.emptyList())
                .stream().findFirst();

        //TEST
//		login = Optional.of("user");

        LOG.trace(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>SystemInterceptor <<<  headers.get( HEADER_USER_LOGIN ) " + login.orElse("NULL"));

        if (isDisplayServiceSchema.isPresent() && Boolean.parseBoolean(isDisplayServiceSchema.get()))
            return;

        if (login.isPresent()) {
            Optional<BasicAuthAccount> accountOpt = basicAuthService.get(login.get());

            if (accountOpt.isPresent()) {
                BasicAuthAccount account = accountOpt.get();
                headers.put(SystemHeadersConstants.HEADER_USER_ID, Collections.singletonList(String.valueOf(account.getId())));

                headers.put(SystemHeadersConstants.HEADER_SYSTEM_UUID, Collections.singletonList(account.getSystemUUID()));

                System system = account.getSystemUUID() != null && !account.getSystemUUID().isEmpty()
                        ? systemService.getByUuid(account.getSystemUUID())
                        : null;
                if (system != null) {
                    headers.put(SystemHeadersConstants.HEADER_SYSTEM_NAME, Collections.singletonList(system.getName()));
                    headers.put(SystemHeadersConstants.HEADER_SYSTEM_ID, Collections.singletonList(String.valueOf(system.getId())));
                }
            } else {
                throw new ForbiddenException();
            }
        }

//        It stops the process
//        else {
//             message.getInterceptorChain().abort();
//        }

    }

    public BasicAuthService getBasicAuthService() {
        return basicAuthService;
    }

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

    public SystemService getSystemService() {
        return systemService;
    }

    public void setSystemService(SystemService systemService) {
        this.systemService = systemService;
    }

}
