package cd.casic.framework.tenant.core.service;


import cd.casic.framework.commons.enums.UserTypeEnum;
import cd.casic.framework.datapermission.service.user.AdminUserService;
import cd.casic.framework.datapermission.service.user.OAuth2TokenService;
import cd.casic.framework.security.dal.oauth2.OAuth2AccessTokenDO;
import cd.casic.framework.security.dal.oauth2.OAuth2CodeDO;
import cd.casic.framework.security.dal.user.AdminUserDO;
import cd.casic.framework.security.oauth2.OAuth2CodeService;
import cd.casic.module.system.enums.ErrorCodeConstants;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static cd.casic.framework.commons.exception.util.ServiceExceptionUtil.exception;

/**
 * OAuth2 授予 Service 实现类
 *
 * @author mianbin modified from yudao
 */
@Slf4j
@Service
public class OAuth2GrantServiceImpl implements OAuth2GrantService {

    @Resource
    private OAuth2TokenService oauth2TokenService;
    @Resource
    private OAuth2CodeService oauth2CodeService;
    @Resource
    private AdminAuthService adminAuthService;
    @Resource
    private AdminUserService adminUserService;

    @Override
    public OAuth2AccessTokenDO grantImplicit(Long userId, Integer userType,
                                             String clientId, List<String> scopes) {
        return oauth2TokenService.createAccessToken(userId, userType, clientId, scopes);
    }

    @Override
    public String grantAuthorizationCodeForCode(Long userId, Integer userType,
                                                String clientId, List<String> scopes,
                                                String redirectUri, String state) {
        return oauth2CodeService.createAuthorizationCode(userId, userType, clientId, scopes,
                redirectUri, state).getCode();
    }

    @Override
    public OAuth2AccessTokenDO grantAuthorizationCodeForAccessToken(String clientId, String code,
                                                                    String redirectUri, String state) {
        OAuth2CodeDO codeDO = oauth2CodeService.consumeAuthorizationCode(code);
        Assert.notNull(codeDO, "授权码不能为空"); // 防御性编程
        // 校验 clientId 是否匹配
        if (!StrUtil.equals(clientId, codeDO.getClientId())) {
            throw exception(ErrorCodeConstants.OAUTH2_GRANT_CLIENT_ID_MISMATCH);
        }
        // 校验 redirectUri 是否匹配
        if (!StrUtil.equals(redirectUri, codeDO.getRedirectUri())) {
            throw exception(ErrorCodeConstants.OAUTH2_GRANT_REDIRECT_URI_MISMATCH);
        }
        // 校验 state 是否匹配
        state = StrUtil.nullToDefault(state, ""); // 数据库 state 为 null 时，会设置为 "" 空串
        if (!StrUtil.equals(state, codeDO.getState())) {
            throw exception(ErrorCodeConstants.OAUTH2_GRANT_STATE_MISMATCH);
        }

        // 创建访问令牌
        return oauth2TokenService.createAccessToken(codeDO.getUserId(), codeDO.getUserType(),
                codeDO.getClientId(), codeDO.getScopes());
    }

    @Override
    public OAuth2AccessTokenDO grantPassword(String username, String password, String clientId, List<String> scopes) {
        // 使用账号 + 密码进行登录
        AdminUserDO user = adminAuthService.authenticate(username, password);
        Assert.notNull(user, "用户不能为空！"); // 防御性编程

        // 创建访问令牌
        return oauth2TokenService.createAccessToken(user.getId(), UserTypeEnum.ADMIN.getValue(), clientId, scopes);
    }

    @Override
    public OAuth2AccessTokenDO grantRefreshToken(String refreshToken, String clientId) {
        return oauth2TokenService.refreshAccessToken(refreshToken, clientId);
    }

    @Override
    public OAuth2AccessTokenDO grantClientCredentials(String clientId, List<String> scopes) {
        // TODO 芋艿：项目中使用 OAuth2 解决的是三方应用的授权，内部的 SSO 等问题，所以暂时不考虑 client_credentials 这个场景
        throw new UnsupportedOperationException("暂时不支持 client_credentials 授权模式");
    }

    @Override
    public boolean revokeToken(String clientId, String accessToken) {
        // 先查询，保证 clientId 时匹配的
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.getAccessToken(accessToken);
        if (accessTokenDO == null || ObjectUtil.notEqual(clientId, accessTokenDO.getClientId())) {
            return false;
        }
        // 再删除
        return oauth2TokenService.removeAccessToken(accessToken) != null;
    }

    @Override
    public String grantIDToken(Long userId, Integer userType, String clientId, List<String> scopes, String nonce) {
        try {
            // 获取用户信息
            AdminUserDO user = adminUserService.getUser(userId);
            if (user == null) {
                throw new IllegalArgumentException("用户不存在");
            }

            // 使用 nimbus-jose-jwt 库生成 ID Token
            // JWT 头部
            JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
                    .type(JOSEObjectType.JWT)
                    .build();

            // JWT 载荷
            JWTClaimsSet.Builder claimsBuilder = new JWTClaimsSet.Builder()
                    .issuer("http://localhost:48080") // iss: 发行者
                    .subject(String.valueOf(userId)) // sub: 主题
                    .audience(clientId) // aud: 受众
                    .expirationTime(new Date(System.currentTimeMillis() + 3600000)) // exp: 过期时间 (1小时)
                    .issueTime(new Date()) // iat: 签发时间
                    .claim("auth_time", new Date()); // auth_time: 认证时间

            // 添加 nonce（如果提供）
            if (StrUtil.isNotBlank(nonce)) {
                claimsBuilder.claim("nonce", nonce);
            }

            // 添加 OIDC 标准声明
            if (scopes.contains("profile")) {
                claimsBuilder.claim("name", user.getNickname());
                claimsBuilder.claim("preferred_username", user.getUsername());
            }

            if (scopes.contains("email")) {
                claimsBuilder.claim("email", user.getEmail());
                claimsBuilder.claim("email_verified", StrUtil.isNotBlank(user.getEmail()));
            }

            JWTClaimsSet claimsSet = claimsBuilder.build();

            // 签名
            SignedJWT signedJWT = new SignedJWT(header, claimsSet);

            // 创建 HMAC signer (实际项目中应使用配置的密钥)
            JWSSigner signer = new MACSigner("your-oidc-secret-key-min-32-chars"); // 密钥至少32字符

            signedJWT.sign(signer);

            return signedJWT.serialize();
        } catch (Exception e) {
            log.error("生成 ID Token 失败", e);
            return "";
        }
    }

}
