package com.jeesharp.business.modules.ai.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.ai.entity.AiFaq;
import com.jeesharp.business.modules.ai.mapper.AiFaqMapper;
import com.jeesharp.business.modules.ai.service.AiFaqService;
import com.jeesharp.business.modules.ai.vo.AiFaqQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class AiFaqServiceImpl extends CrudService<AiFaqMapper, AiFaq, AiFaqQueryVO>
        implements AiFaqService {

    @Override
    @Transactional(readOnly = false)
    public void createFaq(AiFaq entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateFaq(AiFaq entity) {
        update(entity);
    }

    @Override
    public AiFaq matchFaq(String keyword) {
        return matchFaq(null, keyword);
    }

    @Override
    public AiFaq matchFaq(String categoryId, String keyword) {
        if (StrUtil.isBlank(keyword)) {
            return null;
        }
        String trimmed = keyword.trim();
        AiFaqQueryVO query = new AiFaqQueryVO();
        query.setCategoryId(categoryId);
        query.setStatus(1);
        AiFaq keywordHit = null;
        for (AiFaq faq : findList(query)) {
            if (StrUtil.containsIgnoreCase(faq.getQuestion(), trimmed)) {
                return faq;
            }
            if (keywordHit == null && StrUtil.containsIgnoreCase(StrUtil.nullToEmpty(faq.getKeywords()), trimmed)) {
                keywordHit = faq;
            }
            if (keywordHit == null && matchUserMessageContainsFaqKeyword(trimmed, faq.getKeywords())) {
                keywordHit = faq;
            }
        }
        return keywordHit;
    }

    /**
     * 用户输入包含 FAQ 关键词（逗号分隔）时命中，便于「我想问门票」类自然语言。
     */
    private boolean matchUserMessageContainsFaqKeyword(String userMessage, String keywords) {
        if (StrUtil.isBlank(keywords)) {
            return false;
        }
        for (String token : StrUtil.splitTrim(keywords, ',')) {
            if (StrUtil.isNotBlank(token) && StrUtil.containsIgnoreCase(userMessage, token)) {
                return true;
            }
        }
        return false;
    }
}
