<?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.cart.mapper.CartMapper">
  <select id="findByOwner" resultType="com.zioinfo.mall.cart.MallCartItem">
    SELECT c.*, p.name AS product_name, COALESCE(p.sale_price, p.price) AS unit_price, p.thumbnail AS thumbnail,
           o.option_value AS option_label
    FROM mall_cart_item c
    JOIN mall_product p ON p.id = c.product_id
    LEFT JOIN mall_product_option o ON o.id = c.option_id
    WHERE c.owner = #{owner} ORDER BY c.id DESC
  </select>
  <select id="findExisting" resultType="com.zioinfo.mall.cart.MallCartItem">
    SELECT * FROM mall_cart_item WHERE owner = #{owner} AND product_id = #{productId}
    AND (option_id = #{optionId} OR (#{optionId} IS NULL AND option_id IS NULL))
  </select>
  <select id="findById" resultType="com.zioinfo.mall.cart.MallCartItem">SELECT * FROM mall_cart_item WHERE id = #{id}</select>
  <insert id="insert" parameterType="com.zioinfo.mall.cart.MallCartItem" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mall_cart_item (owner, product_id, option_id, size_code, card_message, quantity)
    VALUES (#{owner}, #{productId}, #{optionId}, #{sizeCode}, #{cardMessage}, COALESCE(#{quantity},1))
  </insert>
  <update id="updateQty">UPDATE mall_cart_item SET quantity = #{quantity} WHERE id = #{id} AND owner = #{owner}</update>
  <delete id="delete">DELETE FROM mall_cart_item WHERE id = #{id} AND owner = #{owner}</delete>
  <delete id="clear">DELETE FROM mall_cart_item WHERE owner = #{owner}</delete>
</mapper>
