package com.haha.service;

import com.haha.common.constant.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Redis 服务类
 * 提供基于统一Redis键常量的缓存操作
 */
@Service
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存储Sa-Token相关信息
     */
    public void setSaTokenInfo(String token, String loginId, long timeout) {
        stringRedisTemplate.opsForValue().set(
            String.format(RedisConstants.SA_TOKEN_USER_TOKEN_KEY, token),
            loginId,
            timeout,
            TimeUnit.SECONDS
        );
        stringRedisTemplate.opsForValue().set(
            String.format(RedisConstants.SA_TOKEN_USER_LOGIN_ID_KEY, loginId),
            token,
            timeout,
            TimeUnit.SECONDS
        );
    }

    /**
     * 获取Sa-Token相关信息
     */
    public String getSaTokenByLoginId(String loginId) {
        return stringRedisTemplate.opsForValue().get(
            String.format(RedisConstants.SA_TOKEN_USER_LOGIN_ID_KEY, loginId)
        );
    }

    /**
     * 删除Sa-Token相关信息
     */
    public void deleteSaTokenInfo(String token, String loginId) {
        stringRedisTemplate.delete(String.format(RedisConstants.SA_TOKEN_USER_TOKEN_KEY, token));
        stringRedisTemplate.delete(String.format(RedisConstants.SA_TOKEN_USER_LOGIN_ID_KEY, loginId));
    }

    /**
     * 存储设备状态
     */
    public void setDeviceStatus(String deviceId, String status, long timeout) {
        stringRedisTemplate.opsForValue().set(
            String.format(RedisConstants.DEVICE_STATUS_KEY, deviceId),
            status,
            timeout,
            TimeUnit.SECONDS
        );
    }

    /**
     * 获取设备状态
     */
    public String getDeviceStatus(String deviceId) {
        return stringRedisTemplate.opsForValue().get(
            String.format(RedisConstants.DEVICE_STATUS_KEY, deviceId)
        );
    }

    /**
     * 设置用户信息缓存
     */
    public void setUserInfo(Long userId, String userInfo, long timeout) {
        stringRedisTemplate.opsForValue().set(
            String.format(RedisConstants.USER_INFO_KEY, userId),
            userInfo,
            timeout,
            TimeUnit.SECONDS
        );
    }

    /**
     * 获取用户信息缓存
     */
    public String getUserInfo(Long userId) {
        return stringRedisTemplate.opsForValue().get(
            String.format(RedisConstants.USER_INFO_KEY, userId)
        );
    }
}
