package com.agent.management.repository;

import com.agent.management.model.entity.AgentTemplate;
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.ArrayList;
import java.util.Comparator;
import java.util.List;

@Component
public class AgentTemplateRepository extends AbstractJsonRepository<AgentTemplate> {

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

    @Override
    protected String getFileName() {
        return "agent-templates.json";
    }

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

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

    /** 按 sortOrder 升序、id 升序排序 */
    public List<AgentTemplate> findAllOrderBySort() {
        List<AgentTemplate> list = new ArrayList<>(findAll());
        list.sort(Comparator
                .comparingInt((AgentTemplate t) -> t.getSortOrder() == null ? Integer.MAX_VALUE : t.getSortOrder())
                .thenComparing(AgentTemplate::getId));
        return list;
    }
}
