package com.sonic.cow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.cow.dao.ContextSessionCacheDao;
import com.sonic.cow.domain.entity.ContextSessionCache;
import com.sonic.cow.service.ContextSessionCacheService;
import com.sonic.cow.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ContextSessionCacheServiceImpl extends ServiceImpl<ContextSessionCacheDao, ContextSessionCache> implements ContextSessionCacheService {

    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String getContextId(Long userId, Long toUserId) {
        return stringRedisTemplate.opsForValue().get(redisKeyUtils.chatContextIdCacheKey(userId, toUserId));
    }

    @Override
    public void saveToRedis(Long fromUserId, Long toUserId, String responseId) {
        //写入redis缓存 3天
        String redisKey = redisKeyUtils.chatResponseIdCacheKey(fromUserId, toUserId);
        log.info("===> saveToRedis redisKey : {}, responseId : {}", redisKey, responseId);
        stringRedisTemplate.opsForValue().set(redisKey, responseId, 3, TimeUnit.DAYS);
    }

    @Override
    public String getByRedis(Long fromUserId, Long toUserId) {
        String redisKey = redisKeyUtils.chatResponseIdCacheKey(fromUserId, toUserId);
        String responseId = stringRedisTemplate.opsForValue().get(redisKey);
        log.info("===> getByRedis redisKey : {}, responseId : {}", redisKey, responseId);
        return responseId;
    }

    @Override
    public void deleteRedis(Long fromUserId, Long toUserId) {
        String redisKey = redisKeyUtils.chatResponseIdCacheKey(fromUserId, toUserId);
        stringRedisTemplate.delete(redisKey);
    }

}
