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.ServerInfo;
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(ServerInfo serverInfo) {
        log.info("클라우드_지라_계정전략 :: 계정정보_검증");
        return findAccount(serverInfo);
    }

    @Override
    public AlmAccount getAccount(String connectId) {

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

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

        ServerInfo serverInfo = serverInfoService.verifyServerInfo(connectId);
        return findAccount(serverInfo);
    }

    private AlmAccount findAccount(ServerInfo serverInfo) {
        try {
            String uri = serverInfo.getUri();
            String serverType = serverInfo.getType();
            String apiToken = serverInfoService.getDecryptPasswordOrToken(serverInfo);
            String userId = serverInfo.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());
        }
    }

}
