<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.snack.server.module.favorite.mapper.FavoriteMapper">

    <!-- 结果映射：收藏 + 商品信息 -->
    <resultMap id="FavoriteVOResultMap" type="com.snack.server.module.favorite.vo.FavoriteVO">
        <id column="id" property="id"/>
        <result column="product_id" property="productId"/>
        <result column="product_name" property="productName"/>
        <result column="product_main_image" property="productMainImage"/>
        <result column="min_price" property="minPrice"/>
        <result column="product_status" property="productStatus"/>
        <result column="create_time" property="createTime"/>
    </resultMap>

    <!--
        分页查询用户收藏列表（关联商品信息，减少 IO）
        通过 INNER JOIN product 一次性带出商品名称、主图、状态，
        子查询 product_sku 获取起售价，避免 N+1 查询。
    -->
    <select id="selectFavoritePage" resultMap="FavoriteVOResultMap">
        SELECT
            f.id,
            f.product_id,
            p.name AS product_name,
            p.main_image AS product_main_image,
            (SELECT MIN(price) FROM product_sku WHERE product_id = p.id) AS min_price,
            p.status AS product_status,
            f.create_time
        FROM favorite f
        INNER JOIN product p ON f.product_id = p.id
        WHERE f.user_id = #{userId}
        ORDER BY f.id DESC
    </select>

    <!-- 根据用户 ID 和商品 ID 查询收藏记录 -->
    <select id="selectByUserIdAndProductId" resultType="com.snack.server.module.favorite.entity.Favorite">
        SELECT id, user_id AS userId, product_id AS productId, create_time AS createTime
        FROM favorite
        WHERE user_id = #{userId} AND product_id = #{productId}
        LIMIT 1
    </select>

</mapper>
