package com.chinaweal.aiccs.aiccs.security.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.security.entity.PenaltyAppInfo;
import com.chinaweal.aiccs.aiccs.security.mapper.PenaltyAppInfoMapper;
import com.chinaweal.aiccs.aiccs.security.service.IPenaltyAppInfoService;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 批量吊销外部应用接入信息 服务实现类
 *
 * @author lroyia
 * @since 2026/1/12 16:31
 **/
@Service
public class PenaltyAppInfoServiceImpl extends ServiceImpl<PenaltyAppInfoMapper, PenaltyAppInfo> implements IPenaltyAppInfoService {

    private final static String ACCESS_TOKEN_KEY_PREFIX = "penalty:security:access_token:";

    @Autowired
    private RedisService redisService;

    @Override
    public TUsers getUserInfo(String accessToken) {
        String key = ACCESS_TOKEN_KEY_PREFIX + accessToken;
        if (redisService.exists(key)) {
            String jsonStr = redisService.get(key);
            if (StringUtils.isBlank(jsonStr)) {
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            return JSONObject.parseObject(jsonObject.getJSONObject("user").toJSONString(), TUsers.class);
        }
        return null;
    }

    @Override
    public String generateAccessToken(PenaltyAppInfo appInfo, TUsers user) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appInfo", appInfo);
        jsonObject.put("user", user);
        String accessToken = UUID.randomUUID().toString();
        String key = ACCESS_TOKEN_KEY_PREFIX + accessToken;
        while (redisService.exists(key)) {
            accessToken = UUID.randomUUID().toString();
            key = ACCESS_TOKEN_KEY_PREFIX + accessToken;
        }
        redisService.set(key, jsonObject.toJSONString(), 1800);
        return accessToken;
    }

    @Override
    public void removeAccessToken(String accessToken) {
        redisService.remove(ACCESS_TOKEN_KEY_PREFIX + accessToken);
    }

    @Override
    public boolean existsAccessToken(String accessToken) {
        return redisService.exists(ACCESS_TOKEN_KEY_PREFIX + accessToken);
    }
}
