package com.eactive.eai.rms.onl.apim.approval.apprequest;

import com.eactive.apim.portal.apprequest.entity.AppRequest;
import com.eactive.eai.data.mapper.GenericMapper;
import com.eactive.eai.rms.onl.apim.portalorg.PortalOrgUIMapper;
import com.eactive.eai.rms.onl.transaction.apim.mapping.ApiSpecUIMapper;
import com.eactive.eai.rms.onl.transaction.apim.ui.ApiSpecInfoUI;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.mapstruct.BeanMapping;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.NullValuePropertyMappingStrategy;
import org.mapstruct.ReportingPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Mapper(componentModel = "spring", uses = {PortalOrgUIMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Component
public abstract class AppRequestUIMapper implements GenericMapper<AppRequestUI, AppRequest> {

    @Autowired
    ApiSpecUIMapper apiSpecUIMapper;

    @InheritInverseConfiguration
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    public abstract void updateToEntity(AppRequestUI appRequestUI, @MappingTarget AppRequest appRequest);

    public List<ApiSpecInfoUI> mapApiList(String apiIds) {
        return Arrays.stream(apiIds.split(","))
            .map(String::trim)
            .filter(id -> !id.isEmpty())
            .map(id -> apiSpecUIMapper.getUIById(id))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    public String joinApiList(List<ApiSpecInfoUI> apiList) {
        return apiList.stream()
            .map(ApiSpecInfoUI::getApiId)
            .filter(Objects::nonNull)
            .collect(Collectors.joining(","));
    }
}
