package com.zanxiang.game.module.sdk.service.api;

import com.github.sd4324530.jtuple.Tuple2;
import com.zanxiang.game.module.sdk.pojo.result.PushCpResult;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * @author : lingfeng
 * @time : 2025-01-07
 * @description : CP方充值接口调用
 */
@Slf4j
@Service
public class CpApiService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 回调CP充值接口
     *
     * @param url : 请求链接
     * @return : 返回充值结果以及CP返回结果
     */
    @Retryable(value = {BaseException.class}, maxAttempts = 4, backoff = @Backoff(delay = 5000, multiplier = 2))
    public Tuple2<Boolean, String> callCpRecharge(String url) {
        String resultStr;
        try {
            resultStr = restTemplate.getForObject(url, String.class);
        } catch (Exception e) {
            log.error("回调CP充值接口异常, url : {}, e : {}", url, e.getMessage());
            throw new BaseException("回调CP充值接口异常");
        }
        PushCpResult pushCpResult = JsonUtil.toObj(resultStr, PushCpResult.class);
        if (pushCpResult == null) {
            log.error("CP返回充值结果为空, url : {}, result is null", url);
            throw new BaseException("CP返回充值结果为空");
        }
        boolean pushSuccess = Objects.equals(pushCpResult.getResult(), PushCpResult.SUCCESS_CODE)
                || Objects.equals(pushCpResult.getCode(), PushCpResult.SUCCESS_CODE);
        if (pushSuccess) {
            return Tuple2.with(Boolean.TRUE, resultStr);
        }
        throw new BaseException("CP返回充值失败");
    }
}
