package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.TagData;
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;

@Mapper
public interface GameTagsMapper {

    @Select("""
            <script>
            SELECT gt.game_id
            FROM game_tags gt
            JOIN tags t ON t.id = gt.tag_id AND t.is_active = TRUE
            WHERE t.slug IN
            <foreach item="s" collection="tagSlugs" open="(" separator="," close=")">#{s}</foreach>
            GROUP BY gt.game_id
            HAVING COUNT(DISTINCT t.slug) = #{tagCount}
            </script>
            """)
    List<Long> listGameIdsByTagsAll(@Param("tagSlugs") List<String> tagSlugs, @Param("tagCount") int tagCount);

    @Select("""
            <script>
            SELECT DISTINCT gt.game_id
            FROM game_tags gt
            JOIN tags t ON t.id = gt.tag_id AND t.is_active = TRUE
            WHERE t.slug IN
            <foreach item="s" collection="tagSlugs" open="(" separator="," close=")">#{s}</foreach>
            </script>
            """)
    List<Long> listGameIdsByTagsAny(@Param("tagSlugs") List<String> tagSlugs);

    @Insert("""
            <script>
            INSERT INTO game_tags (game_id, tag_id) VALUES
            <foreach item="tid" collection="tagIds" separator=",">(#{gameId}, #{tid})</foreach>
            ON CONFLICT (game_id, tag_id) DO NOTHING
            </script>
            """)
    void attachTags(@Param("gameId") long gameId, @Param("tagIds") List<Long> tagIds);

    @Select("""
            SELECT
                t.id,
                t.name,
                t.slug,
                t.tag_type AS tagType,
                t.is_active AS isActive,
                t.created_by AS createdBy,
                t.created_at AS createdAt
            FROM game_tags gt
            JOIN tags t ON t.id = gt.tag_id
            WHERE gt.game_id = #{gameId}
              AND t.is_active = TRUE
            ORDER BY t.name ASC
            """)
    List<TagData> listByGame(long gameId);

    @Delete("DELETE FROM game_tags WHERE game_id = #{gameId} AND tag_id = #{tagId}")
    void detach(@Param("gameId") long gameId, @Param("tagId") long tagId);
}
