package es.uv.dagarcos.master.repository;

import es.uv.dagarcos.master.domain.PlayerGlobal;
import es.uv.dagarcos.master.domain.Shard;
import es.uv.dagarcos.master.domain.ShardPlayerStats;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

public interface ShardPlayerStatsRepository extends JpaRepository<ShardPlayerStats, Long> {

    Optional<ShardPlayerStats> findByShardAndPlayer(Shard shard, PlayerGlobal player);

    List<ShardPlayerStats> findByShardOrderByScoreDesc(Shard shard);

    long count();

    @Query("""
        SELECT sps.shard.id, COUNT(sps)
        FROM ShardPlayerStats sps
        GROUP BY sps.shard.id
    """)
    List<Object[]> countPlayersPerShard();

    @Query("""
        SELECT s
        FROM ShardPlayerStats s
        WHERE s.shard.externalId = :shardId
        ORDER BY s.score DESC
    """)
    List<ShardPlayerStats> findByShardOrdered(@Param("shardId") String shardId);

    /*
    @Query("""
        SELECT 
            sps.player.externalPlayerId,
            COUNT(sps.shard.id),
            SUM(sps.totalActions),
            SUM(sps.score)
        FROM ShardPlayerStats sps
        GROUP BY sps.player.id
    """)
    */
    @Query(
        value = """
            SELECT
                p.external_player_id,
                COUNT(s.shard_id),
                SUM(s.total_actions),
                SUM(s.score)
            FROM shard_player_stats s
            JOIN players_global p ON s.player_id = p.id
            GROUP BY p.external_player_id
        """,
        nativeQuery = true
    )
    List<Object[]> aggregateGlobalPlayerStats();

    @Query("""
        SELECT
            sps.player.externalPlayerId,
            SUM(sps.score)
        FROM ShardPlayerStats sps
        GROUP BY sps.player.externalPlayerId
        ORDER BY SUM(sps.score) DESC
    """)
    List<Object[]> globalRanking();

    @Query(""" 
        SELECT
            sps.player.externalPlayerId,
            sps.score
        FROM ShardPlayerStats sps
        WHERE sps.shard.externalId = :shardId
        ORDER BY sps.score DESC
    """)
    List<Object[]> rankingByShard(@Param("shardId") String shardId);

}