package es.uv.dagarcos.master.service;

import es.uv.dagarcos.master.domain.*;
import es.uv.dagarcos.master.dto.ShardPlayerStatsDto;
import es.uv.dagarcos.master.repository.ShardPlayerStatsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ShardPlayerStatsService {

    @Autowired
    private ShardPlayerStatsRepository statsRepository;

    public ShardPlayerStats getOrCreate(Shard shard, PlayerGlobal player) {

        return statsRepository.findByShardAndPlayer(shard, player)
                .orElseGet(() -> {
                    ShardPlayerStats stats = new ShardPlayerStats();
                    stats.setShard(shard);
                    stats.setPlayer(player);
                    stats.setLastUpdatedAt(Instant.now());
                    return statsRepository.save(stats);
                });
    }

    public void updateStats(ShardPlayerStats stats) {
        stats.setLastUpdatedAt(Instant.now());
        statsRepository.save(stats);
    }


    public void applyEvent(ShardPlayerStats stats, MasterEvent event) {

        stats.setTotalActions(stats.getTotalActions() + 1);

        switch (event.getAction()) {
            case "EXPLORE" -> stats.setExplores(stats.getExplores() + 1);
            case "GATHER"  -> stats.setGathers(stats.getGathers() + 1);
            case "FIGHT"   -> stats.setFights(stats.getFights() + 1);
            case "REST"    -> stats.setRests(stats.getRests() + 1);
        }

        if (event.getPointsDelta() != null) {
            stats.setScore(stats.getScore() + event.getPointsDelta());
        }

        stats.setLastUpdatedAt(Instant.now());
        statsRepository.save(stats);
    }

    public List<ShardPlayerStatsDto> getRankingForShard(String shardId) {

        return statsRepository.findByShardOrdered(shardId)
                .stream()
                .map(s -> new ShardPlayerStatsDto(
                        s.getPlayer().getExternalPlayerId(),
                        s.getScore(),
                        s.getTotalActions()
                ))
                .toList();
    }

}