package org.jeecg.modules.adweb.gpt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.adweb.common.util.DateUtil;
import org.jeecg.modules.adweb.gpt.entity.ChatHistory;
import org.jeecg.modules.adweb.gpt.mapper.ChatHistoryMapper;
import org.jeecg.modules.adweb.gpt.service.IChatHistoryService;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description: adweb_ai_chat_history
 * @Author: jeecg-boot
 * @Date: 2025-12-09
 * @Version: V1.0
 */
@Slf4j
@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory>
        implements IChatHistoryService {

    /** 获取用户本周的{@link ChatHistory}记录 */
    @Override
    public ChatHistory getChatHistoryOfWeek(String uid) {
        // 1. 根据uid查询 - 每周对话存储为一条DB记录，date为每周第一天（默认为周一）
        LocalDate firstDayOfWeek = LocalDate.now().with(DayOfWeek.MONDAY);
        ChatHistory chatHistory =
                this.getOne(
                        new LambdaQueryWrapper<ChatHistory>()
                                .eq(ChatHistory::getUid, uid)
                                .ge(ChatHistory::getDate, firstDayOfWeek));
        if (Objects.nonNull(chatHistory)) {
            return chatHistory;
        }

        // 2. 初始化DB entity
        log.info("用户 {} 本周没有对话记录", uid);
        chatHistory = new ChatHistory();
        chatHistory.setUid(uid);
        chatHistory.setDate(firstDayOfWeek);

        // 3. 更新数据库
        this.save(chatHistory);
        return chatHistory;
    }

    /** 获取用户所有的{@link ChatHistory}记录 */
    public List<ChatHistory> getChatHistoriesByUid(String uid) {
        return this.list(new LambdaQueryWrapper<ChatHistory>().eq(ChatHistory::getUid, uid));
    }
}
