package com.arms.api.account.strategy;

import com.arms.api.account.model.AlmAccount;
import com.arms.api.util.alm.JiraUtil;
import com.arms.api.serverinfo.model.vo.ServerInfoVO;
import com.arms.api.serverinfo.service.ServerInfoService;
import com.arms.api.util.errors.ErrorCode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

@Component
@Slf4j
@AllArgsConstructor
public class CloudJiraAccountStrategy implements AccountStrategy {

    private final ServerInfoService serverInfoService;

    private final JiraUtil jiraUtil;

    @Override
    public AlmAccount verifyAccount(ServerInfoVO serverInfoVO) {
        log.info("클라우드_지라_계정전략 :: 계정정보_검증");
        return findAccount(serverInfoVO);
    }

    @Override
    public AlmAccount getAccount(String connectId) {

        log.info("클라우드_지라_계정전략 :: 계정정보_가져오기, 연결_아이디: {}", connectId);

        if (connectId == null) {
            throw new IllegalArgumentException(ErrorCode.PARAMETER_SERVER_ID_MISSING.getErrorMsg());
        }

        ServerInfoVO serverInfoVO = serverInfoService.verifyServerInfo(connectId);
        return findAccount(serverInfoVO);
    }

    private AlmAccount findAccount(ServerInfoVO serverInfoVO) {
        try {
            String uri = serverInfoVO.getUri();
            String serverType = serverInfoVO.getType();
            String apiToken = serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken());
            String userId = serverInfoVO.getUserId();

            log.info("클라우드_지라_계정전략 :: 계정정보_조회, 서버 주소: {}, 서버 타입: {}, apiToken: {}, 유저 아이디: {}",uri,serverType,apiToken,userId);

            WebClient webClient = jiraUtil.createJiraCloudCommunicator(uri, userId, apiToken);

            String endpoint = "/rest/api/3/myself";

            AlmAccount 계정정보_조회결과 = jiraUtil.get(webClient, endpoint, AlmAccount.class).block();

            if (계정정보_조회결과 == null) {
                log.error("클라우드 지라 계정 조회 결과가 Null입니다.");
                throw new IllegalArgumentException(ErrorCode.ACCOUNT_INFO_RETRIEVAL_ERROR.getErrorMsg());
            }

            return 계정정보_조회결과;

        } catch (Exception e) {
            log.error("클라우드 계정 정보 조회시 오류가 발생하였습니다.{}", e.getMessage());
            throw new IllegalArgumentException(ErrorCode.ACCOUNT_INFO_RETRIEVAL_ERROR.getErrorMsg());
        }
    }

}
