package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.JamAwardData;
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 java.util.List;

/**
 * jam_awards CRUD 매퍼 (W2-3 동결 스키마 소비 — docs/jam-eval-ddl.sql §4).
 *
 * <p>일반 테이블 매퍼 → POJO 직접 매핑(snake→camel 비인용 alias). 집계 VIEW 가 아니므로
 * §33 큰따옴표 규칙 비적용(POJO 직접매핑은 비인용 OK).
 *
 * <p>재산정 멱등: deleteByJamTrack(트랙 초기화) → insert(재기록)를 단일 @Transactional
 * 경계(JamAwardService.recompute)에서 수행. score_value 는 트랙별 raw 점수/GRAND 종합점수.
 *
 * <p>SQL 은 전부 `#{}` 바인딩(`${}` 동적치환 0).
 */
@Mapper
public interface JamAwardsMapper {

    @Insert("""
            INSERT INTO jam_awards (jam_id, game_id, award_track, rank, score_value)
            VALUES (#{jamId}, #{gameId}, #{awardTrack}, #{rank}, #{scoreValue})
            """)
    int insert(JamAwardData award);

    @Delete("""
            DELETE FROM jam_awards
            WHERE jam_id = #{jamId}
              AND award_track = #{track}
            """)
    int deleteByJamTrack(@Param("jamId") long jamId, @Param("track") String track);

    @Select("""
            SELECT
                id,
                jam_id        AS jamId,
                game_id       AS gameId,
                award_track   AS awardTrack,
                rank,
                score_value   AS scoreValue,
                computed_at   AS computedAt
            FROM jam_awards
            WHERE jam_id = #{jamId}
            ORDER BY award_track ASC, rank ASC, game_id ASC
            """)
    List<JamAwardData> listByJam(long jamId);

    @Select("""
            SELECT
                a.id,
                a.jam_id        AS jamId,
                a.game_id       AS gameId,
                a.award_track   AS awardTrack,
                a.rank,
                a.score_value   AS scoreValue,
                a.computed_at   AS computedAt,
                g.name          AS gameName,
                g.thumbnail_url AS thumbnailUrl,
                COALESCE(t.name, eu.display_name) AS entrantName
            FROM jam_awards a
            JOIN games g ON g.id = a.game_id
            LEFT JOIN jam_entries e
                ON e.jam_id = a.jam_id AND e.game_id = a.game_id AND e.is_delete IS NOT TRUE
            LEFT JOIN users eu ON eu.id = e.entrant_user_id
            LEFT JOIN jam_teams t ON t.id = e.jam_team_id
            WHERE a.jam_id = #{jamId}
            ORDER BY a.award_track ASC, a.rank ASC, a.game_id ASC
            """)
    List<JamAwardData> listByJamWithGame(long jamId);
}
