package com.agent.management.repository;

import com.agent.management.model.entity.TagAssignment;
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;

@Component
public class TagAssignmentRepository extends AbstractJsonRepository<TagAssignment> {

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

    @Override
    protected String getFileName() {
        return "tag-assignments.json";
    }

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

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

    public List<TagAssignment> findByEntityTypeAndEntityId(String entityType, String entityId) {
        return findAll(a -> Objects.equals(a.getEntityType(), entityType)
                && Objects.equals(a.getEntityId(), entityId));
    }

    public void deleteAllByEntityTypeAndEntityId(String entityType, String entityId) {
        deleteAll(a -> Objects.equals(a.getEntityType(), entityType)
                && Objects.equals(a.getEntityId(), entityId));
    }

    public boolean existsByEntityTypeAndEntityIdAndTagId(String entityType, String entityId, Long tagId) {
        return findAll().stream().anyMatch(a ->
                Objects.equals(a.getEntityType(), entityType)
                && Objects.equals(a.getEntityId(), entityId)
                && Objects.equals(a.getTagId(), tagId));
    }

    /**
     * 批量重命名实体引用（用于 skill folderName 变更时同步标签关联）。
     *
     * @param entityType 实体类型，如 "skill"
     * @param oldEntityId 旧标识（旧 folderName）
     * @param newEntityId 新标识（新 folderName）
     * @return 受影响的关联记录数
     */
    public int renameEntityId(String entityType, String oldEntityId, String newEntityId) {
        if (Objects.equals(oldEntityId, newEntityId)) return 0;
        List<TagAssignment> matches = findByEntityTypeAndEntityId(entityType, oldEntityId);
        if (matches.isEmpty()) return 0;
        matches.forEach(a -> a.setEntityId(newEntityId));
        saveAll(matches);
        return matches.size();
    }
}
