package es.uv.dagarcos.master.service;

import es.uv.dagarcos.master.domain.*;
import es.uv.dagarcos.master.dto.ShardWorldSnapshotDto;
import es.uv.dagarcos.master.repository.MasterEventRepository;
import es.uv.dagarcos.master.repository.PlayerGlobalRepository;
import es.uv.dagarcos.master.repository.ShardWorldSnapshotRepository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ShardWorldSnapshotService {

    @Autowired
    private ShardService shardService;
    @Autowired
    private ShardWorldSnapshotRepository snapshotRepository;
    @Autowired
    private MasterEventRepository masterEventRepository;
    @Autowired
    private PlayerGlobalRepository playerGlobalRepository;

    public void createSnapshot(Shard shard) {

        long totalEvents = masterEventRepository.countByShard(shard);

        long totalPlayers = playerGlobalRepository.count();

        ShardWorldSnapshot snapshot =
                new ShardWorldSnapshot(
                        shard,
                        totalPlayers,
                        totalEvents
                );

        snapshotRepository.save(snapshot);
    }

    public List<ShardWorldSnapshotDto> getSnapshots(String shardId) {
        
        Shard shard = shardService.findByExternalId(shardId);

        return snapshotRepository
                .findByShardOrderBySnapshotAtAsc(shard)
                .stream()
                .map(s -> new ShardWorldSnapshotDto(
                        s.getSnapshotAt(),
                        s.getTotalPlayers(),
                        s.getTotalEvents()
                ))
                .toList();

    }
}