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

import com.eactive.apim.portal.app.entity.Credential;
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 CredentialManService extends BaseService {

    private final CredentialService credentialService;
    private final CredentialUIMapper credentialUIMapper;
    private final PortalOrgService portalOrgService;
    private final PortalOrgUIMapper portalOrgUIMapper;

    public Page<CredentialUI> selectList(Pageable pageable, CredentialSearch credentialSearch) {
        Page<Credential> page = credentialService.findAll(pageable, credentialSearch);
        return page.map(credentialUIMapper::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 CredentialUI selectDetail(String clientId) {
        Credential credential = credentialService.getById(clientId);
        return credentialUIMapper.toVo(credential);
    }

    public void insert(CredentialUI credentialUI) {
        Credential credential = credentialUIMapper.toEntity(credentialUI);
        credential.setAppstatus("1"); // Set default status to normal
        credentialService.save(credential);
    }

    public void update(CredentialUI credentialUI) {
        Credential credential = credentialService.getById(credentialUI.getClientid());
        credentialUIMapper.updateToEntity(credentialUI, credential);
        credentialService.save(credential);
    }

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