package cd.casic.module.system.controller.admin.oauth2;

import cd.casic.framework.commons.pojo.CommonResult;
import cd.casic.framework.datapermission.service.user.AdminUserService;
import cd.casic.framework.security.core.util.SecurityFrameworkUtils;
import cd.casic.framework.security.dal.user.AdminUserDO;
import cd.casic.module.system.dal.dataobject.oidc.OIDCUserInfoRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName OIDCUserInfoController
 * @Date: 2025/7/28 10:56
 * @Description:
 */
@Tag(name = "管理后台 - OIDC 用户信息")
@RestController
@RequestMapping("/system/oidc")
@Validated
@Slf4j
public class OIDCUserInfoController {
    @Resource
    private AdminUserService userService;

    @GetMapping("/userinfo")
    @Operation(summary = "获取 OIDC 用户信息")
    @PreAuthorize("@ss.hasScope('openid')")
    public CommonResult<OIDCUserInfoRespVO> getUserInfo() {
        // 获得用户基本信息
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user = userService.getUser(userId);

        if (user == null) {
            return CommonResult.error(404, "用户不存在");
        }

        OIDCUserInfoRespVO userInfo = new OIDCUserInfoRespVO();
        userInfo.setSub(String.valueOf(user.getId()));
        userInfo.setName(user.getNickname());
        userInfo.setNickname(user.getNickname());
        userInfo.setEmail(user.getEmail());
        // 如果有头像字段可以设置
        // userInfo.setPicture(user.getAvatar());

        return CommonResult.success(userInfo);
    }
}
