package top.tqx.demo_1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.tqx.demo_1.constant.CommonConstant;
import top.tqx.demo_1.entity.KnowledgeBasePath;
import top.tqx.demo_1.entity.User;
import top.tqx.demo_1.mapper.KnowledgeBasePathMapper;
import top.tqx.demo_1.mapper.UserMapper;
import top.tqx.demo_1.service.KnowledgeBasePathService;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class KnowledgeBasePathServiceImpl extends ServiceImpl<KnowledgeBasePathMapper, KnowledgeBasePath> implements KnowledgeBasePathService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<KnowledgeBasePath> getUserAccessibleKnowledgeBases(Long userId, Long deptId, String deptName) {
        User user = userMapper.selectById(userId);
        if (user != null && CommonConstant.RoleType.SUPER_ADMIN.equals(user.getUserType())) {
            List<KnowledgeBasePath> knowledgeBases = this.list();
            log.info("Super admin gets all knowledge bases: userId={}, count={}", userId, knowledgeBases.size());
            return knowledgeBases;
        }

        LambdaQueryWrapper<KnowledgeBasePath> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KnowledgeBasePath::getVisibility, "public");
        wrapper.and(w -> w.eq(KnowledgeBasePath::getOwnerType, "department")
                .and(w1 -> w1.eq(KnowledgeBasePath::getDepartment, deptName)
                        .or().eq(KnowledgeBasePath::getDepartment, "公共部门")));
        wrapper.or(w -> w.eq(KnowledgeBasePath::getOwnerType, "personal")
                .eq(KnowledgeBasePath::getUploader, userId.toString()));

        List<KnowledgeBasePath> knowledgeBases = this.list(wrapper);
        log.info("Get user accessible knowledge bases: userId={}, deptId={}, deptName={}, count={}", userId, deptId, deptName, knowledgeBases.size());
        return knowledgeBases;
    }

    @Override
    public List<String> getUserAccessibleKnowledgeBaseNames(Long userId, Long deptId, String deptName) {
        List<KnowledgeBasePath> knowledgeBases = getUserAccessibleKnowledgeBases(userId, deptId, deptName);
        return knowledgeBases.stream()
                .map(KnowledgeBasePath::getName)
                .collect(Collectors.toList());
    }
}