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.KnowledgeSet;
import com.datamate.datamanagement.infrastructure.persistence.mapper.KnowledgeSetMapper;
import com.datamate.datamanagement.infrastructure.persistence.repository.KnowledgeSetRepository;
import com.datamate.datamanagement.interfaces.dto.KnowledgeSetPagingQuery;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

/**
 * 知识集仓储实现类
 */
@Repository
@RequiredArgsConstructor
public class KnowledgeSetRepositoryImpl extends CrudRepository<KnowledgeSetMapper, KnowledgeSet> implements KnowledgeSetRepository {
    private final KnowledgeSetMapper knowledgeSetMapper;

    @Override
    public KnowledgeSet findByName(String name) {
        return knowledgeSetMapper.selectOne(new LambdaQueryWrapper<KnowledgeSet>().eq(KnowledgeSet::getName, name));
    }

    @Override
    public IPage<KnowledgeSet> findByCriteria(IPage<KnowledgeSet> page, KnowledgeSetPagingQuery query) {
        LambdaQueryWrapper<KnowledgeSet> wrapper = new LambdaQueryWrapper<KnowledgeSet>()
            .eq(query.getStatus() != null, KnowledgeSet::getStatus, query.getStatus())
            .eq(StringUtils.isNotBlank(query.getDomain()), KnowledgeSet::getDomain, query.getDomain())
            .eq(StringUtils.isNotBlank(query.getBusinessLine()), KnowledgeSet::getBusinessLine, query.getBusinessLine())
            .eq(StringUtils.isNotBlank(query.getOwner()), KnowledgeSet::getOwner, query.getOwner())
            .eq(StringUtils.isNotBlank(query.getSensitivity()), KnowledgeSet::getSensitivity, query.getSensitivity())
            .eq(query.getSourceType() != null, KnowledgeSet::getSourceType, query.getSourceType())
            .ge(query.getValidFrom() != null, KnowledgeSet::getValidFrom, query.getValidFrom())
            .le(query.getValidTo() != null, KnowledgeSet::getValidTo, query.getValidTo());

        if (StringUtils.isNotBlank(query.getKeyword())) {
            wrapper.and(w -> w.like(KnowledgeSet::getName, query.getKeyword())
                .or()
                .like(KnowledgeSet::getDescription, query.getKeyword()));
        }

        for (String tagName : query.getTags()) {
            wrapper.and(w ->
                w.apply("tags IS NOT NULL " +
                        "AND JSON_VALID(tags) = 1 " +
                        "AND JSON_LENGTH(tags) > 0 " +
                        "AND JSON_SEARCH(tags, 'one', {0}, NULL, '$[*].name') IS NOT NULL", tagName)
            );
        }

        wrapper.orderByDesc(KnowledgeSet::getCreatedAt);
        return knowledgeSetMapper.selectPage(page, wrapper);
    }
}
