package com.cyksj.service.claude.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.mapper.claudecode.OAuthClientMapper;
import com.cyksj.mapper.claudecode.OAuthTokenMapper;
import com.cyksj.model.entity.OAuthClient;
import com.cyksj.model.entity.OAuthToken;
import com.cyksj.model.request.ClaudeCodeApiKeysReq;
import com.cyksj.model.response.claudecode.ClaudeCodeResp;
import com.cyksj.model.views.ClaudeCodeUserApiKeysView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.claude.ClaudeCodeService;
import com.cyksj.service.claude.OAuthClaudeCodeService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * OAuth服务
 */
@Service
@RequiredArgsConstructor
public class OAuthClaudeCodeServiceImpl implements OAuthClaudeCodeService {

    private final OAuthClientMapper oauthClientMapper;

    private final OAuthTokenMapper oauthTokenMapper;

    private final RedisService redisService;

    private final ClaudeCodeService claudeCodeService;

    /**
     * 验证客户端凭据
     */
    @Override
    public OAuthClient validateClient(String clientId, String clientSecret) {
        QueryWrapper<OAuthClient> wrapper = new QueryWrapper<>();
        wrapper.eq("client_id", clientId)
                .eq("client_secret", clientSecret)
                .eq("status", 1);
        return oauthClientMapper.selectOne(wrapper);
    }

    /**
     * 生成访问令牌
     */
    @Override
    public String generateAccessToken(Long userId, String clientId) throws Exception {
        if (claudeCodeService.checkClaudeCodeUser(userId)) {
            List<ClaudeCodeUserApiKeysView> userApiKeys = claudeCodeService.getUserApiKeys(userId);
            if (CollectionUtil.isEmpty(userApiKeys)) {
                ClaudeCodeApiKeysReq claudeCodeApiKeysReq = new ClaudeCodeApiKeysReq();
                claudeCodeApiKeysReq.setName("系统创建");
                claudeCodeApiKeysReq.setUserId(userId);
                claudeCodeApiKeysReq.setExpiresDays(30);
                ClaudeCodeResp apiKeys = claudeCodeService.createApiKeys(claudeCodeApiKeysReq);
                JSONObject jsonObject = new JSONObject(apiKeys.getData());
                String token = jsonObject.getStr("key_value");
                // 保存token
                OAuthToken oAuthToken = new OAuthToken();
                oAuthToken.setTokenValue(token);
                oAuthToken.setKeyValue(token);
                oAuthToken.setUserId(userId);
                oAuthToken.setClientId(clientId);
                oAuthToken.setStatus(1);
                oAuthToken.setCreatedTime(new Date());

                oauthTokenMapper.insert(oAuthToken);
                return token;

            }else {
                String keyValue = userApiKeys.get(0).getKeyValue();
                OAuthToken oAuthToken = oauthTokenMapper.selectOne(Wrappers.lambdaQuery(OAuthToken.class)
                        .eq(StringUtils.isNotBlank(clientId),OAuthToken::getClientId, clientId)
                        .eq(OAuthToken::getUserId, userId)
                        .eq(OAuthToken::getKeyValue,keyValue)
                );
                if (oAuthToken == null) {
                    oAuthToken = new OAuthToken();
                    oAuthToken.setKeyValue(keyValue);
                    oAuthToken.setClientId(clientId);
                    oAuthToken.setStatus(1);
                    oAuthToken.setUserId(userId);
                    oauthTokenMapper.insert(oAuthToken);
                }else {
                    oAuthToken = new OAuthToken();
                    oAuthToken.setClientId(clientId);
                    oAuthToken.setKeyValue(keyValue);
                    oAuthToken.setStatus(1);
                    oAuthToken.setUserId(userId);
                    oauthTokenMapper.updateById(oAuthToken);
                }
                return userApiKeys.get(0).getKeyValue();
            }
        }

        return null;
    }

    /**
     * 验证访问令牌
     */
    @Override
    public OAuthToken validateToken(String code, String key) {
        LambdaQueryWrapper<OAuthToken> wrapper = Wrappers.lambdaQuery(OAuthToken.class);
        if (StringUtils.isNotBlank(key)) {
            wrapper.eq(OAuthToken::getKeyValue, key).eq(OAuthToken::getStatus, 1);
        } else {
            wrapper.eq(OAuthToken::getTokenValue, key).eq(OAuthToken::getStatus, 1);

        }
        return oauthTokenMapper.selectOne(wrapper);
    }

}