package com.datamate.datamanagement.infrastructure.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.repository.CrudRepository;
import com.datamate.datamanagement.domain.model.knowledge.KnowledgeItem;
import com.datamate.datamanagement.infrastructure.persistence.mapper.KnowledgeItemMapper;
import com.datamate.datamanagement.infrastructure.persistence.repository.KnowledgeItemRepository;
import com.datamate.datamanagement.interfaces.dto.KnowledgeItemPagingQuery;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 知识条目仓储实现类
 */
@Repository
@RequiredArgsConstructor
public class KnowledgeItemRepositoryImpl extends CrudRepository<KnowledgeItemMapper, KnowledgeItem> implements KnowledgeItemRepository {
    private final KnowledgeItemMapper knowledgeItemMapper;

    @Override
    public IPage<KnowledgeItem> findByCriteria(IPage<KnowledgeItem> page, KnowledgeItemPagingQuery query) {
        LambdaQueryWrapper<KnowledgeItem> wrapper = new LambdaQueryWrapper<KnowledgeItem>()
            .eq(StringUtils.isNotBlank(query.getSetId()), KnowledgeItem::getSetId, query.getSetId())
            .eq(query.getContentType() != null, KnowledgeItem::getContentType, query.getContentType())
            .eq(query.getSourceType() != null, KnowledgeItem::getSourceType, query.getSourceType())
            .eq(StringUtils.isNotBlank(query.getSourceDatasetId()), KnowledgeItem::getSourceDatasetId, query.getSourceDatasetId())
            .eq(StringUtils.isNotBlank(query.getSourceFileId()), KnowledgeItem::getSourceFileId, query.getSourceFileId());

        if (StringUtils.isNotBlank(query.getKeyword())) {
            wrapper.and(w -> w.like(KnowledgeItem::getSourceFileId, query.getKeyword())
                .or()
                .like(KnowledgeItem::getContent, query.getKeyword()));
        }

        wrapper.orderByDesc(KnowledgeItem::getCreatedAt);
        return knowledgeItemMapper.selectPage(page, wrapper);
    }

    @Override
    public long countBySetId(String setId) {
        return knowledgeItemMapper.selectCount(new LambdaQueryWrapper<KnowledgeItem>()
            .eq(KnowledgeItem::getSetId, setId));
    }

    @Override
    public List<KnowledgeItem> findAllBySetId(String setId) {
        return knowledgeItemMapper.selectList(new LambdaQueryWrapper<KnowledgeItem>()
            .eq(KnowledgeItem::getSetId, setId)
            .orderByDesc(KnowledgeItem::getCreatedAt));
    }
}
