package com.arms.api.issue.schedule.controller;

import com.arms.api.issue.almapi.model.dto.AlmIssueIncrementDTO;
import com.arms.api.issue.almapi.model.dto.AlmIssueWithRequirementDTO;
import com.arms.api.issue.almapi.model.dto.증분이슈수집RequestDTO;
import com.arms.api.issue.almapi.model.entity.AlmIssueEntity;
import com.arms.api.issue.almapi.model.dto.CReqProperty;
import com.arms.api.issue.schedule.service.IssueScheduleService;
import com.arms.api.util.aspect.DwrSendAlarm;
import com.arms.api.util.aspect.SlackSendAlarm;
import com.arms.api.util.msa_communicate.DwrBackendCoreClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.arms.api.issue.almapi.model.dto.AlmIssueIncrementDTO.*;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/engine/jira")
public class IssueScheduleController {

    private final IssueScheduleService issueScheduleService;

    private final DwrBackendCoreClient dwrBackendCoreClient;

    @ResponseBody
    @GetMapping("/{connectId}/issue/get/{reqProjectKey}/{reqIssueKey}")
    public AlmIssueEntity findIssueByRecentId(@PathVariable("connectId") Long connectId,
                                    @PathVariable("reqProjectKey") String reqProjectKey,
                                    @PathVariable("reqIssueKey") String reqIssueKey) {

        String recentId = connectId + "_" + reqProjectKey + "_" + reqIssueKey;

        log.info("[ 이슈_스케줄_컨트롤러 :: 요구사항이슈_조회 ] :: 조회조건_아이디 = {}", recentId);

        return issueScheduleService.findIssueByRecentId(recentId);
    }

    @PostMapping("/{connectId}/issue/pre-process/req-status-to-es")
    public void preSaveReqStatus(
            @PathVariable("connectId") String connectId,
            @RequestParam("cTitle") String cTitle,
            @RequestParam("cReqStatusId") Long cReqStatusId,
            @RequestParam("issueKey") String issueKey,
            @RequestParam("pdServiceId") Long pdServiceId,
            @RequestParam("pdServiceVersions") List<Long> pdServiceVersions,
            @RequestParam("cReqLink") Long cReqLink,
            @RequestParam("projectKeyOrId") String projectKeyOrId,
            CReqProperty CReqProperty
    ){

        AlmIssueWithRequirementDTO almIssueWithRequirementDTO = new AlmIssueWithRequirementDTO();
        almIssueWithRequirementDTO.setJiraServerId(connectId);
        almIssueWithRequirementDTO.setCTitle(cTitle);
        almIssueWithRequirementDTO.setCReqStatusId(cReqStatusId);
        almIssueWithRequirementDTO.setIssueKey(issueKey);
        almIssueWithRequirementDTO.setServiceId(pdServiceId);
        almIssueWithRequirementDTO.setVersions(pdServiceVersions);
        almIssueWithRequirementDTO.setCReqLink(cReqLink);
        almIssueWithRequirementDTO.setCReqProperty(CReqProperty);
        almIssueWithRequirementDTO.setProjectKeyOrId(projectKeyOrId);

        issueScheduleService.preSaveReqStatus(almIssueWithRequirementDTO);
    }


    @Async
    @DwrSendAlarm(messageOnStart = "ALM 수집 시작(ALM TO ES)",messageOnEnd = "ALM 수집 완료(ALM TO ES)")
    @SlackSendAlarm(messageOnStart = "ALM 수집 시작(ALM TO ES)",messageOnEnd = "ALM 수집 완료(ALM TO ES)")
    @PostMapping("/issue/loadToES/bulk/increment")
    public void discoverIncrementalIssues(@RequestBody 증분이슈수집RequestDTO requestDTO) {

        log.info("[ IssueScheduleController :: discoverIncrementalIssues start] :: serverProjectInfos size : {}, startDate : {}, endDate : {}",
                requestDTO.getServerProjectInfos() != null ? requestDTO.getServerProjectInfos().size() : 0,
                requestDTO.getStartDate(),
                requestDTO.getEndDate());

        List<AlmIssueEntity> allCollectedIssues = new ArrayList<>();

        for (증분이슈수집RequestDTO.ServerProjectInfo serverProjectInfo : requestDTO.getServerProjectInfos()) {

            AlmIssueIncrementDTO almIssueIncrementDTO
                    = builder()
                        .serverId(serverProjectInfo.getServerId())
                        .projectKey(serverProjectInfo.getProjectKey())
                        .startDate(requestDTO.getStartDate())
                        .endDate(requestDTO.getEndDate())
                    .build();

            List<AlmIssueEntity> collectedIssues = issueScheduleService.discoveryIncrementALmIssue(almIssueIncrementDTO);

            if (collectedIssues != null && !collectedIssues.isEmpty()) {
                allCollectedIssues.addAll(collectedIssues);
            }

        }

        log.info("[ IssueScheduleController :: discoverIncrementalIssues ] :: 총 수집된 요구사항 수 = {}", allCollectedIssues.size());

        try {
            dwrBackendCoreClient.transferAlmDataToBackend(allCollectedIssues);
            log.info("[ IssueScheduleController :: discoverIncrementalIssues ] :: Backend-Core 동기화 요청 완료");
        } catch (Exception e) {
            log.error("[ IssueScheduleController :: discoverIncrementalIssues ] :: Backend-Core 동기화 요청 실패", e);
        }

        log.info("[ IssueScheduleController :: discoverIncrementalIssues end] ");

    }

    @ResponseBody
    @GetMapping("/issue/test/api-request")
    public void cloudJiraTestApiRequest() {
         issueScheduleService.cloudJiraTestApiRequest();
    }

    @ResponseBody
    @PostMapping("/sync-data/delete-if-does-not-exist-doc")
    public void deleteIfDoesNotExistDoc() {
         issueScheduleService.deleteIfDoesNotExistDoc();
    }


    @PutMapping("/arms-state-category")
    public ResponseEntity<?> updateArmsStateCategory() {
        issueScheduleService.updateArmsStateCategory();
        return ResponseEntity.ok("OK");
    }


}
