package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.JamEntryData;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface JamEntriesMapper {

    @Insert("""
            INSERT INTO jam_entries (
                jam_id,
                game_id,
                entrant_type,
                entrant_user_id,
                jam_team_id
            ) VALUES (
                #{jamId},
                #{gameId},
                #{entrantType},
                #{entrantUserId},
                #{jamTeamId}
            )
            """)
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(JamEntryData entry);

    @Select("""
            SELECT
                e.id,
                e.jam_id AS jamId,
                e.game_id AS gameId,
                e.entrant_type AS entrantType,
                e.entrant_user_id AS entrantUserId,
                e.jam_team_id AS jamTeamId,
                e.submitted_at AS submittedAt,
                e.is_delete AS isDelete,
                g.name AS gameName,
                g.thumbnail_url AS thumbnailUrl,
                COALESCE(t.name, eu.display_name) AS entrantName
            FROM jam_entries e
            JOIN games g ON g.id = e.game_id AND g.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 e.jam_id = #{jamId}
              AND e.is_delete IS NOT TRUE
            ORDER BY e.submitted_at DESC, e.id DESC
            """)
    List<JamEntryData> listByJam(long jamId);

    @Select("""
            SELECT EXISTS(
                SELECT 1
                FROM jam_entries
                WHERE jam_id = #{jamId}
                  AND game_id = #{gameId}
                  AND is_delete IS NOT TRUE
            )
            """)
    boolean exists(@Param("jamId") long jamId, @Param("gameId") long gameId);

    @Select("""
            SELECT EXISTS(
                SELECT 1 FROM jam_entries e
                WHERE e.jam_id = #{jamId} AND e.game_id = #{gameId} AND e.is_delete IS NOT TRUE
                  AND (
                    (e.entrant_type = 'USER' AND e.entrant_user_id = #{userId})
                    OR
                    (e.entrant_type = 'TEAM' AND EXISTS(
                        SELECT 1 FROM jam_team_members m
                        WHERE m.jam_team_id = e.jam_team_id AND m.user_id = #{userId}
                    ))
                  )
            )
            """)
    boolean isOwnEntry(@Param("jamId") long jamId, @Param("gameId") long gameId, @Param("userId") long userId);
}
