package top.tqx.demo_1.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.tqx.demo_1.entity.FAQ;
import top.tqx.demo_1.entity.FAQSuggestion;
import top.tqx.demo_1.mapper.FAQMapper;
import top.tqx.demo_1.mapper.FAQSuggestionMapper;
import top.tqx.demo_1.service.FAQSuggestionService;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FAQSuggestionServiceImpl implements FAQSuggestionService {

    private final FAQSuggestionMapper faqSuggestionMapper;
    private final FAQMapper faqMapper;

    @Override
    public FAQSuggestion save(FAQSuggestion suggestion) {
        faqSuggestionMapper.insert(suggestion);
        log.info("保存FAQ建议: id={}", suggestion.getId());
        return suggestion;
    }

    @Override
    public FAQSuggestion findById(Long id) {
        return faqSuggestionMapper.selectById(id);
    }

    @Override
    public List<FAQSuggestion> findByStatus(String status) {
        return faqSuggestionMapper.selectByStatus(status);
    }

    @Override
    public FAQSuggestion approve(Long id, String answer) {
        FAQSuggestion suggestion = faqSuggestionMapper.selectById(id);
        if (suggestion != null) {
            FAQ faq = new FAQ();
            faq.setQuestion(suggestion.getQuery());
            faq.setAnswer(answer);
            faq.setStatus("approved");
            faqMapper.insert(faq);

            suggestion.setStatus("approved");
            suggestion.setFaqId(faq.getId());
            suggestion.setAnswer(answer);
            faqSuggestionMapper.updateById(suggestion);
            log.info("审批通过FAQ建议: suggestionId={}, faqId={}", id, faq.getId());
        }
        return suggestion;
    }

    @Override
    public void reject(Long id) {
        faqSuggestionMapper.updateStatus(id, "rejected");
        log.info("拒绝FAQ建议: id={}", id);
    }

    @Override
    public void updateFrequency(Long id, Integer frequency) {
        faqSuggestionMapper.updateFrequency(id, frequency);
    }

    @Override
    public FAQSuggestion findOrCreate(String query, String answer) {
        FAQSuggestion existing = faqSuggestionMapper.selectByQuery(query);
        if (existing != null) {
            existing.setFrequency(existing.getFrequency() + 1);
            faqSuggestionMapper.updateById(existing);
            return existing;
        }
        FAQSuggestion newSuggestion = new FAQSuggestion();
        newSuggestion.setQuery(query);
        newSuggestion.setAnswer(answer);
        newSuggestion.setFrequency(1);
        newSuggestion.setStatus("pending");
        faqSuggestionMapper.insert(newSuggestion);
        return newSuggestion;
    }
}