<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zioinfo.mall.review.mapper.ReviewMapper">
  <select id="findByProduct" resultType="com.zioinfo.mall.review.MallReview">
    SELECT * FROM mall_review WHERE product_id = #{productId} ORDER BY id DESC LIMIT #{limit}
  </select>
  <select id="findById" resultType="com.zioinfo.mall.review.MallReview">SELECT * FROM mall_review WHERE id = #{id}</select>
  <insert id="insert" parameterType="com.zioinfo.mall.review.MallReview" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mall_review (product_id, order_id, author, rating, title, content, image_url, store_id, helpful_count)
    VALUES (#{productId}, #{orderId}, #{author}, #{rating}, #{title}, #{content}, #{imageUrl}, #{storeId}, 0)
  </insert>
  <delete id="delete">DELETE FROM mall_review WHERE id = #{id} AND author = #{author}</delete>
  <update id="incHelpful">UPDATE mall_review SET helpful_count = COALESCE(helpful_count,0) + 1 WHERE id = #{id}</update>
  <select id="stats" resultType="java.util.Map">
    SELECT COALESCE(ROUND(AVG(rating)::numeric,2),0) AS avg, COUNT(*) AS cnt FROM mall_review WHERE product_id = #{productId}
  </select>
  <update id="applyStats">
    UPDATE mall_product SET
      rating_avg = (SELECT COALESCE(ROUND(AVG(rating)::numeric,2),0) FROM mall_review WHERE product_id = #{productId}),
      review_count = (SELECT COUNT(*) FROM mall_review WHERE product_id = #{productId})
    WHERE id = #{productId}
  </update>
  <select id="recentContents" resultType="string">
    SELECT content FROM mall_review WHERE product_id = #{productId} AND content IS NOT NULL ORDER BY id DESC LIMIT #{limit}
  </select>
</mapper>
