package cn.edu.whu.boot.user.services.impl;

import cn.edu.whu.boot.user.services.PermissionCacheService;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class PermissionCacheServiceImpl implements PermissionCacheService {

    private final StringRedisTemplate redisTemplate;

    private final SetOperations<String, String> setOps;

    public PermissionCacheServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.setOps = this.redisTemplate.opsForSet();
    }

    @Override
    public Set<String> getPermissionsByRole(int role) {
        return setOps.members(getKey(role));
    }

    @Override
    public void deletePermissionsByRole(int role) {
        redisTemplate.delete(getKey(role));
    }

    @Override
    public void addPermissions(int role, String[] permissions) {
        String key = getKey(role);
        Boolean keyExists = redisTemplate.hasKey(key);
        setOps.add(key, permissions);
        if (keyExists != null && keyExists.equals(false)) {
            // 如果是首次创建，则设置过期时间
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
        }
    }

    @Override
    public boolean permissionsCached(int role) {
        Boolean keyExists = redisTemplate.hasKey(getKey(role));
        return keyExists != null && keyExists;
    }

    private String getKey(int role) {
        return String.format("roles:%d:permissions", role);
    }
}
