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

import com.icomsys.main_vm.biz.advice.excep.CustomBadRequestException;
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.login.service.LoginService;
import com.icomsys.main_vm.biz.rcp.conversation.vo.ConversationApiNodeEditReq;
import com.icomsys.main_vm.biz.rcp.conversation.vo.ConversationApiNodeInfoRes;
import com.icomsys.main_vm.biz.rcp.conversation.vo.LongtextManagerVO;
import com.icomsys.main_vm.common.code.code.LongTextManagerColumnCode;
import com.icomsys.main_vm.common.code.code.LongTextManagerTableCode;
import com.icomsys.main_vm.common.code.enumresource.ActionResource;
import com.icomsys.main_vm.common.code.enumresource.MenuResource;
import com.icomsys.main_vm.common.util.HashUtil;
import com.icomsys.main_vm.db.jpa.entity.scenario.TbApiNode;
import com.icomsys.main_vm.db.jpa.entity.scenario.TbLongtextManager;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbApiNodeRepo;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbLongtextManagerRepo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class ConversationApiNodeEditService {

    private final LoginService loginService;
    private final LogService logService;

    private final TbLongtextManagerRepo tbLongtextManagerRepo;

    private final TbApiNodeRepo tbApiNodeRepo;


    @Transactional
    public int insertApiNode(ConversationApiNodeEditReq dto) throws CustomBadRequestException{

        String userId = loginService.getUserVo().getUserId();
        LocalDateTime currentDateTime = LocalDateTime.now();
        String oprMngCode = dto.getCustCode() + "_RCP_" +  dto.getServiceGroup();

        TbApiNode vo = new TbApiNode();
        vo.setNodeName(dto.getNodeName());
        vo.setUseYn("Y");
        vo.setRegistId(userId);
        vo.setRegistDate(currentDateTime);
        vo.setUpdateId(userId);
        vo.setUpdateDate(currentDateTime);
        vo.setOprMngCode(oprMngCode);

        TbApiNode result = tbApiNodeRepo.save(vo);

        TbLongtextManager vo1 = new TbLongtextManager();
        String checkSum;

        try {
            checkSum = HashUtil.getStringToChecksum(dto.getTextContents());
        } catch (NoSuchAlgorithmException e) {
            throw new CustomBadRequestException("API node 해시값 생성에 실패하였습니다.");
        }

        vo1.setRfSeq(result.getSeq());
        vo1.setTableCode(LongTextManagerTableCode.TB_API_NODE.getCode());
        vo1.setColumnCode(LongTextManagerColumnCode.CONTENT.getCode());
        vo1.setChecksum(checkSum);
        vo1.setTextContents(dto.getTextContents());
        tbLongtextManagerRepo.save(vo1);

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

        return Math.toIntExact(result.getSeq());
    }

    @Transactional
    public int updateApiNode(ConversationApiNodeEditReq dto) throws CustomBadRequestException {
        if (dto.getNodeName() == null || dto.getNodeName().isEmpty()) {
            throw new CustomBadRequestException("API Node명을 입력해주세요");
        }

        String checkSum;
        try {
            checkSum = HashUtil.getStringToChecksum(dto.getTextContents());
        } catch (NoSuchAlgorithmException e) {
            throw new CustomBadRequestException("API node 해시값 생성에 실패하였습니다.");
        }

        LongtextManagerVO vo = new LongtextManagerVO();
        vo.setTextContents(dto.getTextContents());
        vo.setTableCode(LongTextManagerTableCode.TB_API_NODE.getCode());
        vo.setColumnCode(LongTextManagerColumnCode.CONTENT.getCode());
        vo.setChecksum(checkSum);
        vo.setRfSeq(dto.getSeq());

        tbLongtextManagerRepo.updateApiLongTextManager(vo);
        tbApiNodeRepo.updateApiNode(dto);

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

        return 0;
    }

    public HashMap selectApiNode(HashMap map) {
        Long seq = Long.parseLong(String.valueOf(map.get("seq")));
        LongtextManagerVO vo = new LongtextManagerVO();
        vo.setRfSeq(seq);
        vo.setColumnCode(LongTextManagerColumnCode.CONTENT.getCode());
        vo.setTableCode(LongTextManagerTableCode.TB_API_NODE.getCode());
        List<LongtextManagerVO> list = tbLongtextManagerRepo.selectLongTextManager(vo);
        List<ConversationApiNodeInfoRes> list1 = tbApiNodeRepo.selectApiNode(seq);

        HashMap map1 = new HashMap();
        map1.put("apiData", list);
        map1.put("apiDataInfo", list1);

        return map1;
    }

}
