package com.arms.api.account.strategy;

import com.arms.api.account.model.AlmAccount;
import com.arms.api.account.model.RedmineAccount;
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.api.util.errors.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class OnPromiseRedmineAccountStrategy implements AccountStrategy {

    private final Logger 로그 = LoggerFactory.getLogger(this.getClass());

    private final ServerInfoService serverInfoService;

    private final RedmineUtil redmineUtil;

    @Autowired
    public OnPromiseRedmineAccountStrategy(ServerInfoService ServerInfoService, RedmineUtil RedmineUtil) {
        this.serverInfoService = ServerInfoService;
        this.redmineUtil = RedmineUtil;
    }

    @Override
    public AlmAccount verifyAccount(ServerInfoVO serverInfoVO) {
        로그.info("레드마인_온프레미스_계정_전략 :: 계정정보_검증");

        return 계정정보_조회(serverInfoVO);
    }

    @Override
    public AlmAccount getAccount(String connectId) {
        로그.info("레드마인_온프레미스_계정_전략 :: 계정정보_가져오기");

        ServerInfoVO serverInfoVO = serverInfoService.verifyServerInfo(connectId);

        return 계정정보_조회(serverInfoVO);
    }

    private AlmAccount 계정정보_조회(ServerInfoVO serverInfoVO) {

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

            로그.info("레드마인_온프레미스_계정_전략 :: 계정정보_조회, 서버 주소: {}, 서버 타입: {}, apiToken: {}, 유저 아이디: {}",uri,serverType,apiToken,userId);

            String endpoint = "/my/account.json";

            WebClient webClient = redmineUtil.createRedmineWebClientCommunicator(uri,serverInfoService.getDecryptPasswordOrToken(serverInfoVO.getPasswordOrToken()));

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

            if (계정정보_조회결과 == null) {
                로그.error("온프라미스 레드마인 계정 조회 결과가 Null입니다.");
                throw new IllegalArgumentException(ErrorCode.ACCOUNT_INFO_RETRIEVAL_ERROR.getErrorMsg());
            }else{
                return  계정정보_데이터_변환(계정정보_조회결과 , uri);
            }
        }
        catch (Exception e){
            로그.error("온프라미스 레드마인 계정 정보 조회시 오류가 발생하였습니다." + e.getMessage());
            throw new IllegalArgumentException(ErrorCode.ACCOUNT_INFO_RETRIEVAL_ERROR.getErrorMsg());
        }

    }

    private AlmAccount 계정정보_데이터_변환(RedmineAccount 계정정보_조회결과, String uri){

        AlmAccount AlmAccount = new AlmAccount();

        String self = uri+"users/"+계정정보_조회결과.getUser().getId()+".json";
        AlmAccount.setSelf(self);
        AlmAccount.setName(계정정보_조회결과.getUser().getLogin());
        AlmAccount.setDisplayName(계정정보_조회결과.getUser().getLastname());
        AlmAccount.setEmailAddress(계정정보_조회결과.getUser().getMail());
        AlmAccount.setAdmin(계정정보_조회결과.getUser().getAdmin());
        AlmAccount.setApiKey(계정정보_조회결과.getUser().getApiKey());

        return AlmAccount;
    }

}
