package com.icomsys.main_vm.biz.rcp.conversation.service;

import com.icomsys.main_vm.biz.advice.excep.CustomNotFoundException;
import com.icomsys.main_vm.biz.common.common.service.LogService;
import com.icomsys.main_vm.biz.common.common.service.LogVO;
import com.icomsys.main_vm.biz.common.system.vo.DslDataTableRes;
import com.icomsys.main_vm.biz.rcp.conversation.vo.ConversationApiNodeInfoReq;
import com.icomsys.main_vm.biz.rcp.conversation.vo.ConversationApiNodeInfoRes;
import com.icomsys.main_vm.common.code.enumresource.ActionResource;
import com.icomsys.main_vm.common.code.enumresource.MenuResource;
import com.icomsys.main_vm.db.jpa.entity.system.TbServiceGrouop;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbApiNodeRepo;
import com.icomsys.main_vm.db.jpa.repo.system.TbServiceGrouopRepo;
import com.querydsl.core.QueryResults;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * Name : ConversationApiNodeService
 * date : 2023-02-07
 * author :  Mong
 * description :
 * ===========================================================
 * DATE                 AUTHOR                NOTE
 * -----------------------------------------------------------
 * 2023-02-07                Mong             최초 생성
 */

@Service
@RequiredArgsConstructor
@Slf4j
public class ConversationApiNodeService {

    private final TbApiNodeRepo tbApiNodeRepo;
    private final TbServiceGrouopRepo tbServiceGrouopRepo;
    private final LogService logService;

    public DslDataTableRes<ConversationApiNodeInfoRes> searchApiNodeList(ConversationApiNodeInfoReq dto) throws CustomNotFoundException {
        if (dto.isContainUpper()) {     // 상위 그룹포함 검색일 경우
            TbServiceGrouop serviceGrouop = tbServiceGrouopRepo.findByServiceGroup(dto.getServiceGroup())
                    .orElseThrow(() -> new CustomNotFoundException("서비스 그룹 정보가 없습니다."));

            dto.setServiceGroupUpper(serviceGrouop.getServiceGroupUpper());
        }

        QueryResults<ConversationApiNodeInfoRes> result = tbApiNodeRepo.searchApiNodeList(dto);
        return new DslDataTableRes<ConversationApiNodeInfoRes>(result);
    }

    @Transactional
    public int deleteApiNode(HashMap map){
        Long seq = Long.parseLong(String.valueOf(map.get("seq")));
        String serviceGroup = String.valueOf(map.get("serviceGroup"));
        tbApiNodeRepo.deleteApiNode(seq);

        logService.LogSave(LogVO.builder()
                .menuAuth(MenuResource.rcpconversationapiNodemanage)
                .actionCode(ActionResource.delete.getName())
                .serviceGroup(serviceGroup)
                .build());

        return 0;
    }

}
