package es.uv.dagarcos.master.service;

import es.uv.dagarcos.master.domain.Shard;
import es.uv.dagarcos.master.domain.ShardStatus;
import es.uv.dagarcos.master.repository.ShardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;

@Service
public class ShardService {

    @Autowired
    private ShardRepository shardRepository;

    public Shard findByExternalId(String externalId) {
        return shardRepository.findByExternalId(externalId)
                .orElseThrow(() ->
                        new IllegalArgumentException("Shard no registrado: " + externalId));
    }

    public List<Shard> findAll() {
        return shardRepository.findAll();
    }

    public void markStarted(Shard shard) {
        shard.setStatus(ShardStatus.STARTED);
        shard.setStartedAt(Instant.now());
        shard.setLastHeartbeat(Instant.now());
        shardRepository.save(shard);
    }

    public void updateHeartbeat(Shard shard) {
        shard.setLastHeartbeat(Instant.now());
        shardRepository.save(shard);
    }

    public void markStopped(Shard shard) {
        shard.setStatus(ShardStatus.STOPPED);
        shardRepository.save(shard);
    }
}