package com.vetti.web.controller.hotake;

import com.vetti.common.annotation.Anonymous;
import com.vetti.common.core.domain.AjaxResult;
import com.vetti.common.core.domain.R;
import com.vetti.common.utils.SecurityUtils;
import com.vetti.hotake.domain.HotakeSocialUser;
import com.vetti.hotake.domain.dto.HotakeSocialLoginRequestDto;
import com.vetti.hotake.domain.dto.HotakeSocialLoginResultDto;
import com.vetti.hotake.service.IHotakeSocialUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 社交登录控制器
 *
 * @author vetti
 */
@Api(tags = "社交登录模块")
@RestController
@RequestMapping("/oauth2")
public class HotakeSocialLoginController {

    @Autowired
    private IHotakeSocialUserService socialUserService;

    /**
     * 获取OAuth授权URL
     */
    @Anonymous
    @ApiOperation("获取OAuth授权URL")
    @GetMapping("/authorize/{provider}")
    public R<String> getAuthorizationUrl(
            @ApiParam(value = "平台类型：google/microsoft/linkedin", required = true)
            @PathVariable String provider,
            @ApiParam(value = "state参数，用于防止CSRF攻击")
            @RequestParam(required = false) String state) {
        String authUrl = socialUserService.getAuthorizationUrl(provider, state);
        return R.ok(authUrl, "");
    }

    /**
     * 社交登录回调（用code换取token并登录）
     */
    @Anonymous
    @ApiOperation("社交登录")
    @PostMapping("/login")
    public R<HotakeSocialLoginResultDto> socialLogin(@Validated @RequestBody HotakeSocialLoginRequestDto requestDto) {
        HotakeSocialLoginResultDto resultDto = socialUserService.socialLogin(requestDto);
        return R.ok(resultDto, "");
    }

    /**
     * 获取当前用户绑定的社交账号列表
     */
    @ApiOperation("获取当前用户绑定的社交账号列表")
    @GetMapping("/bindList")
    public R<List<HotakeSocialUser>> getBindList() {
        Long userId = SecurityUtils.getUserId();
        List<HotakeSocialUser> list = socialUserService.listByUserId(userId);
        // 脱敏处理，不返回token等敏感信息
        list.forEach(item -> {
            item.setAccessToken(null);
            item.setRefreshToken(null);
            item.setRawUserInfo(null);
        });
        return R.ok(list, "");
    }

    /**
     * 解绑社交账号
     */
    @ApiOperation("解绑社交账号")
    @DeleteMapping("/unbind/{provider}")
    public AjaxResult unbind(
            @ApiParam(value = "平台类型：google/microsoft/linkedin", required = true)
            @PathVariable String provider) {
        Long userId = SecurityUtils.getUserId();
        socialUserService.unbind(userId, provider);
        return AjaxResult.success("解绑成功");
    }
}
