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

import com.eactive.eai.data.entity.onl.b2bextractor.B2BExtractId;
import com.eactive.eai.data.entity.onl.message.ServiceMessageEntity;
import com.eactive.eai.data.mapper.BaseMapperConfig;
import com.eactive.eai.data.mapper.GenericMapper;
import com.eactive.eai.rms.data.entity.onl.b2bextract.B2bExtractService;
import com.eactive.eai.rms.onl.loader.intf.deploy.ServiceMessageDeploy;
import org.mapstruct.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


@Mapper(config = BaseMapperConfig.class, uses = { EAIReferenceMessageDeployMapper.class, CondPerRtgInfoDeployMapper.class })
@Transactional
public abstract class ServiceMessageDeployMapper implements GenericMapper<ServiceMessageDeploy, ServiceMessageEntity> {

    @Autowired private B2bExtractService b2bExtractService;
    @Autowired private B2BExtractDeployMapper b2BExtractDeployMapper;

    @Mapping(source = "id.eaisvcname", target = "eaisvcname")
    @Mapping(source = "id.svcprcssno", target = "svcprcssno")
    @Mapping(source = "condPerRtgInfos", target = "condPerRtgInfoDeploys")
    @Mapping(source = "eaiReferenceMessages", target = "eaiReferenceMessageDeploys")
    public abstract ServiceMessageDeploy toVo(ServiceMessageEntity serviceMessageEntity);

    @InheritInverseConfiguration
    public abstract ServiceMessageEntity toEntity(ServiceMessageDeploy serviceMessageDeploy);

    @AfterMapping
    public void mapAfterToVo(ServiceMessageEntity entity, @MappingTarget ServiceMessageDeploy vo) {
        b2bExtractService
                .findById(new B2BExtractId(entity.getId().getEaisvcname(), entity.getId().getSvcprcssno()))
                .map(b2BExtractDeployMapper::toVo)
                .ifPresent(vo::setB2BExtractDeploy);
    }

}
