package org.lingniu.sdk.web;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.lingniu.sdk.model.base.CommonResult;
import org.lingniu.sdk.model.user.UserInfo;
import org.lingniu.sdk.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RequestMapping("/idp")
@RestController
public class UserController {

    private final OAuth2ClientProperties oAuth2ClientProperties;
    private final ObjectMapper objectMapper;

    public UserController(OAuth2ClientProperties oAuth2ClientProperties, ObjectMapper objectMapper) {
        this.oAuth2ClientProperties = oAuth2ClientProperties;
        this.objectMapper = objectMapper;
    }

    @GetMapping("/routes")
    public CommonResult<Object> getUserMenu(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient oAuth2AuthorizedClient) throws Exception {
        OAuth2AccessToken.TokenType tokenType = oAuth2AuthorizedClient.getAccessToken().getTokenType();
        String tokenValue = oAuth2AuthorizedClient.getAccessToken().getTokenValue();

        String s = HttpClientUtils.get(oAuth2ClientProperties.getProvider().get("idp").getUserInfoUri().replace("userinfo","idp/getRouters"),
                Map.of("Authorization",tokenType.getValue() + " " + tokenValue,"Accept","application/json"));
        return CommonResult.success(objectMapper.readValue(s,Map.class).get("data"));
    }
}
