package com.rj.repository;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;
import java.util.List;

/**
 * Author: 李中华  wx: spllzh  email(qq): 28668817@qq.com
 * Date: 2025/8/4 17:39
 **/
@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        //获取当前会话id的 聊天列表，是json串
        String chatMessageListJson = redisTemplate.opsForValue().get(memoryId.toString());

        // 把JSON转换成会话列表
        List<ChatMessage> chatMessages = ChatMessageDeserializer.messagesFromJson(chatMessageListJson);

        return chatMessages;
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {

        //把会话列表转换成JSON
        String chatMessageListJson = ChatMessageSerializer.messagesToJson(list);

        //更新当前会话id的值，保存到Redis里
        redisTemplate.opsForValue().set(memoryId.toString(), chatMessageListJson, Duration.ofDays(1));

    }

    @Override
    public void deleteMessages(Object memoryId) {
            // 删除当前会话id的值
        redisTemplate.delete(memoryId.toString());
    }
}
