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

import com.eactive.apim.portal.app.entity.ProdClient;
import com.eactive.apim.portal.portalorg.entity.PortalOrg;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.onl.apim.portalorg.PortalOrgService;
import com.eactive.eai.rms.onl.apim.portalorg.PortalOrgUI;
import com.eactive.eai.rms.onl.apim.portalorg.PortalOrgUIMapper;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
@RequiredArgsConstructor
public class ProdClientManService extends BaseService {

    private final ProdClientService prodClientService;
    private final ProdClientUIMapper prodClientUIMapper;
    private final PortalOrgService portalOrgService;
    private final PortalOrgUIMapper portalOrgUIMapper;

    public Page<ProdClientUI> selectList(Pageable pageable, ProdClientSearch prodClientSearch) {
        Page<ProdClient> page = prodClientService.findAll(pageable, prodClientSearch);
        return page.map(prodClientUIMapper::toVo);
    }

    public HashMap<String, Object> selectDetailCombo() {
        List<PortalOrg> portalOrgList = portalOrgService.findByOrgStatusAndApprovalStatus("ACTIVE", "COMPLETED");
        List<PortalOrgUI> portalOrgUIList = portalOrgList.stream()
            .map(portalOrgUIMapper::toVo)
            .collect(Collectors.toList());

        HashMap<String, Object> map = new HashMap<>();
        map.put("portalOrgList", portalOrgUIList);
        return map;
    }

    public ProdClientUI selectDetail(String clientId) {
        ProdClient prodClient = prodClientService.getById(clientId);
        return prodClientUIMapper.toVo(prodClient);
    }

    public void insert(ProdClientUI prodClientUI) {
        ProdClient prodClient = prodClientUIMapper.toEntity(prodClientUI);
        prodClient.setAppstatus("1"); // Set default status to normal
        prodClientService.save(prodClient);
    }

    public void update(ProdClientUI prodClientUI) {
        ProdClient prodClient = prodClientService.getById(prodClientUI.getClientid());
        prodClientUIMapper.updateToEntity(prodClientUI, prodClient);
        prodClientService.save(prodClient);
    }

    public void delete(String clientId) {
        prodClientService.deleteById(clientId);
    }
}
