package com.agent.management.service.impl;

import com.agent.management.common.exception.BusinessException;
import com.agent.management.model.entity.KbCategory;
import com.agent.management.repository.KbCategoryRepository;
import com.agent.management.repository.KbDocumentRepository;
import com.agent.management.service.KbCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class KbCategoryServiceImpl implements KbCategoryService {

    private final KbCategoryRepository categoryRepository;
    private final KbDocumentRepository documentRepository;

    @Override
    public KbCategory create(Long parentId, String name) {
        if (name == null || name.trim().isEmpty()) {
            throw new BusinessException("分类名称不能为空");
        }
        if (parentId != null && !categoryRepository.existsById(parentId)) {
            throw new BusinessException(404, "父分类不存在");
        }
        KbCategory c = new KbCategory();
        c.setName(name.trim());
        c.setParentId(parentId);
        c.setSortOrder(0);
        return categoryRepository.save(c);
    }

    @Override
    public KbCategory update(Long id, String name, Long parentId, Integer sortOrder) {
        KbCategory c = categoryRepository.findById(id)
                .orElseThrow(() -> new BusinessException(404, "分类不存在"));
        if (name != null && !name.trim().isEmpty()) {
            c.setName(name.trim());
        }
        if (parentId != null) {
            if (parentId.equals(id)) {
                throw new BusinessException("不能将分类的父节点设为自己");
            }
            if (!categoryRepository.existsById(parentId)) {
                throw new BusinessException(404, "父分类不存在");
            }
            c.setParentId(parentId);
        }
        if (sortOrder != null) {
            c.setSortOrder(sortOrder);
        }
        return categoryRepository.save(c);
    }

    @Override
    public void delete(Long id) {
        KbCategory c = categoryRepository.findById(id)
                .orElseThrow(() -> new BusinessException(404, "分类不存在"));
        // 拒绝删除非空分类（有子分类或文档）
        if (categoryRepository.existsByParentId(id)) {
            throw new BusinessException("分类下有子分类，请先删除子分类");
        }
        if (documentRepository.countByCategoryId(id) > 0) {
            throw new BusinessException("分类下有文档，请先移动或删除文档");
        }
        categoryRepository.delete(c);
    }

    @Override
    public List<KbCategory> listAll() {
        return categoryRepository.findAllByOrderBySortOrderAscNameAsc();
    }

    @Override
    public List<KbCategory> listChildren(Long parentId) {
        return categoryRepository.findByParentIdOrderBySortOrderAscNameAsc(parentId);
    }

    @Override
    public KbCategory get(Long id) {
        return categoryRepository.findById(id)
                .orElseThrow(() -> new BusinessException(404, "分类不存在"));
    }
}
