package com.storlead.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.knowledge.entity.AiMessageEntity;
import com.storlead.knowledge.mapper.AiMessageMapper;
import com.storlead.knowledge.pojo.dto.QueryPageDTO;
import com.storlead.knowledge.service.AiMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * AI对话消息记录 服务实现类
 * </p>
 *
 * @author storlead
 * @since 2026-06-09
 */
@Service
public class AiMessageServiceImpl extends MyBaseServiceImpl<AiMessageMapper, AiMessageEntity> implements AiMessageService {

    @Override
    public IPage<AiMessageEntity> pageQuery(QueryPageDTO page) {
        Page<AiMessageEntity> pageParam = new Page<>(page.getPageIndex(), page.getPageSize());
        LambdaQueryWrapper<AiMessageEntity> wrapper = new LambdaQueryWrapper<>();

        // 如果有关键字，搜索 query 和 answer 字段
        if (StringUtils.isNotBlank(page.getKeyword())) {
            wrapper.and(w -> w
                    .like(AiMessageEntity::getQuery, page.getKeyword())
                    .or()
                    .like(AiMessageEntity::getAnswer, page.getKeyword())
            );
        }

        // 按创建时间降序排列
        wrapper.orderByDesc(AiMessageEntity::getCreatedAt);

        return pageWithScope(pageParam, wrapper);
    }
}
