package com.sonic.frog.client.impl;

import com.alibaba.fastjson.JSON;
import com.mashape.unirest.http.Unirest;
import com.sonic.frog.client.DiscordOauth2Client;
import com.sonic.frog.client.dto.DiscordTokenResponse;
import com.sonic.frog.client.dto.DiscordUserResponse;
import com.sonic.frog.domain.bo.ThirdAuthBo;
import com.sonic.frog.enums.BizResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DiscordOauth2ClientImpl implements DiscordOauth2Client {

    @Value("${thirdLogin.discord.clientID}")
    private String clientID ;
    @Value("${thirdLogin.discord.clientSecret}")
    private String clientSecret ;
    @Value("${thirdLogin.discord.redirectUri}")
    private String redirectUri ;
    @Value("${thirdLogin.discord.scope}")
    private String scope;

    @Override
    public ThirdAuthBo getDiscordIdByToken(String code) {
        ThirdAuthBo thirdAuthBo = new ThirdAuthBo();
        try {
            //参考文档地址：https://discord.com/developers/docs/resources/user
            //Step1: 根据code码来获取授权Token
            String accessToken = getAccessTokenByCode(code);
            //Step2: 根据授权Token获取用户自己的基础信息
            String response = Unirest.get("https://discord.com/api/v6/users/@me")
                    .header("Authorization", "Bearer "+ accessToken).asString().getBody();
            log.info("===> getDiscordIdByToken result : {}",response);
            DiscordUserResponse discordUserResponse = JSON.parseObject(response, DiscordUserResponse.class);

            thirdAuthBo.setThirdId(discordUserResponse.getId());
            thirdAuthBo.setNickname(discordUserResponse.getUsername());
            //在这里我们只取用户认证过的邮箱，没有认证的邮箱是无效的，取出来也没用
            if(Boolean.TRUE.toString().equals(discordUserResponse.getVerified())) {
                thirdAuthBo.setEmail(discordUserResponse.getEmail());
            }
            return thirdAuthBo;
        } catch (Exception e) {
            log.error("discord get token by code error", e);
            BizResultCode.DISCORD_NETWORK_ERROR.check(true);
        }
        return thirdAuthBo;
    }

    /**
     * 根据code码来获取访问用户基础信息的token
     * @param code
     * @return
     */
    public String getAccessTokenByCode(String code) {
        String accessToken = "";
        try {
            String response = Unirest.post("https://discord.com/api/v6/oauth2/token")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .field("client_id", clientID)
                    .field("client_secret", clientSecret)
                    .field("grant_type", "authorization_code")
                    .field("code", code)
                    .field("redirect_uri", redirectUri)
                    .field("scope", scope).asString().getBody();
            log.info("===> getAccessTokenByCode : {}", response);
            DiscordTokenResponse discordTokenResponse = JSON.parseObject(response, DiscordTokenResponse.class);
            return discordTokenResponse.getAccess_token();
        } catch (Exception e) {
            log.error("===> discord get token by code error ", e);
            BizResultCode.DISCORD_NETWORK_ERROR.check(true);
        }
        return accessToken;
    }

}
