package com.arms.api.issue.priority.strategy;

import com.arms.api.issue.priority.model.IssuePriorityDTO;
import com.arms.api.serverinfo.model.vo.ServerInfoVO;
import com.arms.api.serverinfo.service.ServerInfoService;
import com.arms.api.util.alm.JiraApi;
import com.arms.api.util.alm.JiraUtil;
import com.arms.api.util.errors.ErrorLogUtil;
import lombok.AllArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;

@Component
@AllArgsConstructor
public class CloudJiraIssuePriorityStrategy implements IssuePriorityStrategy {

    private final JiraUtil jiraUtil;

    private final JiraApi jiraApi;

    private final ServerInfoService serverInfoService;

    @Override
    public List<IssuePriorityDTO> getIssuePriorityList(ServerInfoVO serverInfoVO) {

        WebClient webClient = jiraUtil.createJiraCloudCommunicator(serverInfoVO.getUri(), serverInfoVO.getUserId(), serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken()));
        String priorityEndpoint = jiraApi.getEndpoint().getIssue().getPriority();

        try {

            return jiraUtil.get(webClient, priorityEndpoint,
                    new ParameterizedTypeReference<List<IssuePriorityDTO>>() {}).block();
        }
        catch (Exception e) {
            String errorMessage = ErrorLogUtil.exceptionLoggingAndReturn(e, this.getClass().getName(),
                    String.format("%s[%s] :: getIssuePriorityList Error", serverInfoVO.getType(), serverInfoVO.getUri()));
            throw new IllegalArgumentException(errorMessage);
        }
    }
}
