package com.schisandra.auth.application.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.schisandra.auth.application.factory.OauthTypeHandlerFactory;
import com.schisandra.auth.application.handler.oauth.SchisandraOauthTypeHandler;
import com.schisandra.auth.common.entity.Result;
import com.schisandra.auth.common.redis.RedisUtil;
import com.schisandra.auth.domain.service.SchisandraAuthUserDomainService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * ClassName:SchisandraOauthController
 * Package:com.schisandra.auth.application.controller
 * Description:实现justauth第三方登录
 *
 * @Author:fanyang
 * @Create:2024/5/9 - 21:30
 * @Version: v1.0
 */

@Slf4j
@RestController
@RequestMapping("/oauth/")
public class SchisandraOauthController {
    @Resource
    private OauthTypeHandlerFactory oauthTypeHandlerFactory;

    @Resource
    private SchisandraAuthUserDomainService schisandraAuthUserDomainService;


    @Value("${web.url}")
    private String url;


    /**
     * @description: 获取授权链接并跳转到第三方授权页面
     * @param: []
     * @return: com.schisandra.auth.common.entity.Result
     * {@code @author:} landaiqing
     * @date: 2024/5/26 0:26
     */
    @GetMapping("/render/{type}")
    public Result<String> renderAuth(@PathVariable("type") String type) throws IOException {
        AuthRequest authRequest = getAuthRequest(type);
        String token = AuthStateUtils.createState();
        String url = authRequest.authorize(token);
        return Result.ok(url);
    }

    private AuthRequest getAuthRequest(String type) {
        SchisandraOauthTypeHandler handler = oauthTypeHandlerFactory.getHandler(type);
        AuthRequest authRequest = handler.getAuthRequest(type);
        return authRequest;
    }

    /**
     * @description: 回调函数
     * @param: [callback]
     * @return: void
     * @author: landaiqing
     * @date: 2024/5/26 13:20
     */
    @GetMapping("/callback/{type}")
    @SneakyThrows
    public void login(@PathVariable("type") String type, AuthCallback callback, HttpServletResponse response) {
        AuthRequest authRequest = getAuthRequest(type);
        AuthResponse<AuthUser> authResponse = authRequest.login(callback);
        AuthUser data = authResponse.getData();
        AuthToken token = data.getToken();
        Result result = schisandraAuthUserDomainService.insertAuthUserByOauth(data, type);
        if (result.getSuccess()){
            response.sendRedirect(url + "loading?token=" + token.getAccessToken() + "&userId=" + StpUtil.getLoginIdAsString());
        }else{
            log.error("登录失败");
        }
    }

}

