package com.arms.api.issue.almapi.service;

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.vo.AlmIssueWithRequirementVO;
import com.arms.api.issue.almapi.model.dto.CReqProperty;
import com.arms.api.issue.almapi.model.entity.AlmIssueEntity;
import com.arms.api.serverinfo.model.vo.ServerInfoVO;
import com.arms.api.serverinfo.service.ServerInfoService;
import com.arms.api.util.alm.RedmineUtil;
import com.arms.egovframework.javaservice.esframework.model.vo.DocumentResultWrapper;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryWrapper;
import com.arms.egovframework.javaservice.esframework.esquery.SimpleQuery;
import com.taskadapter.redmineapi.Include;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.bean.Issue;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;

import java.util.*;
import java.util.function.Function;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@SpringBootTest(properties = {
        "spring.profiles.active=dev",
        "arms-index-name.jiraissue=test_jiraissue",
        "arms-index-name.serverinfo=test_serverinfo"
})
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class RedmineDiscoveryTest
//        extends WireMockRedmineConfig
{

    @Autowired
    IssueService issueService;

    @Autowired
    RedmineUtil redmineUtil;

    @Autowired
    ServerInfoService serverInfoService;

    @MockitoBean
    CategoryMappingService categoryMappingService;

    @Autowired
    EsCommonRepositoryWrapper<AlmIssueEntity> esCommonRepositoryWrapper;


    @BeforeEach
    void 요구사항키_셋업() {
//
        esCommonRepositoryWrapper.deleteIndex(-1);
        esCommonRepositoryWrapper.saveEmpty(new AlmIssueEntity());

        when(categoryMappingService.getMappingCategory(any(),any(),any(),any()))
                .thenReturn("");

        List<String> issueKeys = List.of("1", "15", "5", "55", "56", "58", "59", "7", "8");

        for (String issueKey : issueKeys) {
            AlmIssueWithRequirementDTO almIssueWithRequirementDTO = new AlmIssueWithRequirementDTO();
            almIssueWithRequirementDTO.setJiraServerId("1750099904565629634");
            almIssueWithRequirementDTO.setIssueKey(issueKey);
            almIssueWithRequirementDTO.setServiceId(1L);
            almIssueWithRequirementDTO.setVersions(List.of(1L));
            almIssueWithRequirementDTO.setProjectKeyOrId("11");
            almIssueWithRequirementDTO.setCReqLink(1L);
            CReqProperty cReqProperty = new CReqProperty();
            cReqProperty.setCReqPriorityLink(1L);
            almIssueWithRequirementDTO.setCReqProperty(cReqProperty);

            issueService.preSaveReqStatus(almIssueWithRequirementDTO);

        }
    }


    @Test
    public void 레드마인_증분_테스트_2025_05_14_2025_07_21() throws Exception {

        List<String> values = Arrays.asList("10", "11");
        Collections.shuffle(values);

        for (String projectKey : values) {
            AlmIssueIncrementDTO almIssueIncrementDTO = AlmIssueIncrementDTO.builder()
                    .serverId("1750099904565629634")
                    .projectKey(projectKey)
                    .startDate("2025-08-11")
                    .endDate("2025-08-11")
                    .build();
            List<AlmIssueEntity> almIssueEntities = issueService.discoveryIncrementALmIssueAndGetReqAlmIssueEntities(almIssueIncrementDTO);
        }


    }

    @Test
    public void 전체_수집_다음_증분_수집() throws Exception {
        List<String> projects = Arrays.asList("10", "11");
        Collections.shuffle(projects);

        for (String projectKey : projects) {
            AlmIssueIncrementDTO almIssueIncrementDTO = AlmIssueIncrementDTO.builder()
                    .serverId("1750099904565629634")
                    .projectKey(projectKey)
                    .startDate("2025-05-20")
                    .endDate("2025-07-21")
                    .build();
            List<AlmIssueEntity> almIssueEntities = issueService.discoveryIncrementALmIssueAndGetReqAlmIssueEntities(almIssueIncrementDTO);
        }


        데이터_검증();
    }

    public void 데이터_검증(){

        DocumentResultWrapper<AlmIssueEntity> findRecentHits
                = esCommonRepositoryWrapper.findRecentHits(SimpleQuery.termQueryFilter("jira_server_id","1750099904565629634"));

        List<AlmIssueEntity> docs = findRecentHits.toDocs();

        ServerInfoVO serverInfoVO = serverInfoService.verifyServerInfo("1750099904565629634");

        RedmineManager redmineManager = redmineUtil.createRedmineOnPremiseCommunicator(serverInfoVO.getUri(), serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken()));

        Function<String,LinkedListVO> retrieveAlmF = (str)->this.issueList(str,redmineManager);

        new EsDataValidationTest(esCommonRepositoryWrapper,retrieveAlmF).dataValid(docs);
    }

    private LinkedListVO issueList(String key, RedmineManager redmineManager) {
        Set<String> linkedIssueSet = new HashSet<>();
        try {
            Issue issueById = redmineManager.getIssueManager().getIssueById(Integer.parseInt(Objects.requireNonNull(key)), Include.relations, Include.children);
            issueById.getRelations()
                    .stream().filter(Objects::nonNull).forEach(a->{
                        linkedIssueSet.add(String.valueOf( a.getIssueId()));
                        linkedIssueSet.add(String.valueOf(a.getIssueToId()));
                    });
            return new LinkedListVO(String.valueOf(issueById.getProjectId()),String.valueOf(issueById.getId()),linkedIssueSet.stream().toList());
        } catch (RedmineException e) {
            throw new RuntimeException(e);
        }
    }

}
