package com.eactive.eai.rms.onl.loader.intf;

import com.eactive.eai.rms.data.entity.onl.b2bextract.B2bExtractService;
import com.eactive.eai.rms.data.entity.onl.bizkey.BizKeyService;
import com.eactive.eai.rms.data.entity.onl.eaimsg.EAIMessageService;
import com.eactive.eai.rms.data.entity.onl.stdmessage.StandardMessageInfoService;
import com.eactive.eai.rms.data.entity.onl.submessage.SubMessageInfoService;
import com.eactive.eai.rms.onl.loader.intf.deploy.EAIMessageDeploy;
import com.eactive.eai.rms.onl.loader.intf.deploy.ServiceMessageDeploy;
import com.eactive.eai.rms.onl.loader.intf.mapper.*;
import com.eactive.eai.rms.onl.loader.service.DeployService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.stream.Collectors;

@Service("OnlInterfaceDeployService")
@Transactional
@RequiredArgsConstructor
public class InterfaceDeployService extends DeployService {

    private final EAIMessageService eaiMessageService;
    private final EAIMessageDeployMapper eaiMessageDeployMapper;

    private final BizKeyService bizKeyService;
    private final BizKeyDeployMapper bizKeyDeployMapper;

    private final B2bExtractService b2bExtractService;
    private final B2BExtractDeployMapper b2BExtractDeployMapper;

    private final StandardMessageInfoService standardMessageInfoService;
    private final StandardMessageInfoDeployMapper standardMessageInfoDeployMapper;

    private final SubMessageInfoService subMessageInfoService;
    private final SubMessageInfoDeployMapper subMessageInfoDeployMapper;

    public EAIMessageDeploy selectDeploy(String eaisvcname) {
        return eaiMessageService.findById(eaisvcname).map(eaiMessageDeployMapper::toVo).orElse(null);
    }

    public void saveDeploy(EAIMessageDeploy eaiMessageDeploy) {
        deleteAndSave(eaiMessageDeploy, eaiMessageDeployMapper, eaiMessageService);

        deleteExistsAndSaveAll(eaiMessageDeploy.getBizKeyDeploys(), bizKeyDeployMapper, bizKeyService);
        deleteExistsAndSaveAll(eaiMessageDeploy.getStandardMessageInfoDeploys(), standardMessageInfoDeployMapper, standardMessageInfoService);
        deleteExistsAndSaveAll(eaiMessageDeploy.getSubMessageInfoDeploys(), subMessageInfoDeployMapper, subMessageInfoService);
        deleteExistsAndSaveAll(
                eaiMessageDeploy.getServiceMessages().stream().map(ServiceMessageDeploy::getB2BExtractDeploy).filter(Objects::nonNull).collect(Collectors.toList()),
                b2BExtractDeployMapper, b2bExtractService);
    }

}
