package com.agent.management.repository;

import com.agent.management.model.entity.SkillCategory;
import com.agent.management.repository.json.AbstractJsonRepository;
import com.agent.management.repository.json.JsonStore;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Component
public class SkillCategoryRepository extends AbstractJsonRepository<SkillCategory> {

    public SkillCategoryRepository(JsonStore store) {
        super(store, new TypeReference<>() {});
    }

    @Override
    protected String getFileName() {
        return "skill-category-mappings.json";
    }

    @Override
    protected Long getId(SkillCategory entity) {
        return entity.getId();
    }

    @Override
    protected void setId(SkillCategory entity, Long id) {
        entity.setId(id);
    }

    public Optional<SkillCategory> findBySkillFolderName(String skillFolderName) {
        return findAll(sc -> Objects.equals(sc.getSkillFolderName(), skillFolderName))
                .stream().findFirst();
    }

    public List<SkillCategory> findByCategoryIdIn(List<Long> categoryIds) {
        return findAll(sc -> categoryIds.contains(sc.getCategoryId()));
    }

    public void deleteBySkillFolderName(String skillFolderName) {
        deleteAll(sc -> Objects.equals(sc.getSkillFolderName(), skillFolderName));
    }

    public List<SkillCategory> findByCategoryId(Long categoryId) {
        return findAll(sc -> Objects.equals(sc.getCategoryId(), categoryId));
    }

    /**
     * 批量重命名技能目录引用（用于 skill folderName 变更时同步分类关联）。
     *
     * @param oldFolderName 旧 folderName
     * @param newFolderName 新 folderName
     * @return 受影响的关联记录数
     */
    public int renameSkillFolderName(String oldFolderName, String newFolderName) {
        if (Objects.equals(oldFolderName, newFolderName)) return 0;
        List<SkillCategory> matches = findAll(sc -> Objects.equals(sc.getSkillFolderName(), oldFolderName));
        if (matches.isEmpty()) return 0;
        matches.forEach(sc -> sc.setSkillFolderName(newFolderName));
        saveAll(matches);
        return matches.size();
    }
}
