package es.uv.dagarcos.master.repository;

import es.uv.dagarcos.master.domain.Shard;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.Instant;
import java.util.Optional;

public interface ShardRepository extends JpaRepository<Shard, Long> {

    Optional<Shard> findByExternalId(String externalId);

    boolean existsByExternalId(String externalId);

    long count();

    @Query("""
        SELECT COUNT(s)
        FROM Shard s
        WHERE s.lastHeartbeat IS NOT NULL
          AND s.lastHeartbeat > :threshold
    """)
    long countActiveShards(@Param("threshold") Instant threshold);

}