package com.pandoli365.bibimbap.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * 게임잼 인기투표(잼당 1인 1표) 매퍼.
 */
@Mapper
public interface JamVotesMapper {

    @Insert("""
            INSERT INTO jam_votes (jam_id, game_id, voter_user_id)
            VALUES (#{jamId}, #{gameId}, #{voterUserId})
            """)
    int castVote(@Param("jamId") long jamId,
                 @Param("gameId") long gameId,
                 @Param("voterUserId") long voterUserId);

    @Update("""
            UPDATE jam_votes
            SET game_id = #{gameId}
            WHERE jam_id = #{jamId}
              AND voter_user_id = #{voterUserId}
            """)
    int updateVote(@Param("jamId") long jamId,
                   @Param("voterUserId") long voterUserId,
                   @Param("gameId") long gameId);

    @Delete("""
            DELETE FROM jam_votes
            WHERE jam_id = #{jamId}
              AND voter_user_id = #{voterUserId}
            """)
    int deleteVote(@Param("jamId") long jamId,
                   @Param("voterUserId") long voterUserId);

    @Select("""
            SELECT game_id
            FROM jam_votes
            WHERE jam_id = #{jamId}
              AND voter_user_id = #{voterUserId}
            """)
    Long findVotedGameId(@Param("jamId") long jamId,
                         @Param("voterUserId") long voterUserId);

    @Select("""
            SELECT COUNT(*)
            FROM jam_votes
            WHERE jam_id = #{jamId}
            """)
    long countByJam(@Param("jamId") long jamId);

    @Select("""
            SELECT game_id AS "gameId", COUNT(*) AS "voteCount"
            FROM jam_votes
            WHERE jam_id = #{jamId}
            GROUP BY game_id
            ORDER BY COUNT(*) DESC, game_id ASC
            """)
    List<Map<String, Object>> listCountsByJam(@Param("jamId") long jamId);
}
