package com.pandoli365.bibimbap.mapper;

import com.pandoli365.bibimbap.data.ReviewAxisRow;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;

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

@Mapper
public interface GameReviewAxesMapper {

    @InsertProvider(type = AxesSqlProvider.class, method = "insertAxes")
    int addReviewAxes(@Param("reviewId") long reviewId, @Param("axes") List<ReviewAxisRow> axes);

    @Delete("DELETE FROM game_review_axes WHERE review_id = #{reviewId}")
    int deleteReviewAxes(@Param("reviewId") long reviewId);

    @SelectProvider(type = AxesSqlProvider.class, method = "listByReviewIds")
    List<ReviewAxisRow> listAxesByReviewIds(@Param("reviewIds") List<Long> reviewIds);

    class AxesSqlProvider {

        // VALUES 다행. 각 값은 #{axes[i].axisKey}/#{axes[i].score} 바인딩(${} 미사용).
        public String insertAxes(Map<String, Object> params) {
            @SuppressWarnings("unchecked")
            List<ReviewAxisRow> axes = (List<ReviewAxisRow>) params.get("axes");
            StringBuilder sql = new StringBuilder("INSERT INTO game_review_axes (review_id, axis_key, score) VALUES ");
            for (int i = 0; i < axes.size(); i++) {
                if (i > 0) {
                    sql.append(", ");
                }
                sql.append("(#{reviewId}, #{axes[").append(i).append("].axisKey}, #{axes[").append(i).append("].score})");
            }
            return sql.toString();
        }

        // IN (...) batch. reviewIds 각 원소 #{reviewIds[i]} 바인딩.
        public String listByReviewIds(Map<String, Object> params) {
            @SuppressWarnings("unchecked")
            List<Long> ids = (List<Long>) params.get("reviewIds");
            SQL sql = new SQL();
            sql.SELECT("review_id AS reviewId, axis_key AS axisKey, score").FROM("game_review_axes");
            StringBuilder in = new StringBuilder();
            for (int i = 0; i < ids.size(); i++) {
                if (i > 0) {
                    in.append(", ");
                }
                in.append("#{reviewIds[").append(i).append("]}");
            }
            sql.WHERE("review_id IN (" + in + ")");
            return sql.toString();
        }
    }
}
