<?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.inventory.mapper.StoreInventoryMapper">
  <select id="findByStore" resultType="com.zioinfo.mall.inventory.MallStoreInventory">
    SELECT si.*, p.name AS product_name, p.thumbnail
    FROM mall_store_inventory si JOIN mall_product p ON p.id = si.product_id
    WHERE si.store_id = #{storeId} ORDER BY p.id
  </select>
  <select id="findOne" resultType="com.zioinfo.mall.inventory.MallStoreInventory">
    SELECT * FROM mall_store_inventory WHERE store_id = #{storeId} AND product_id = #{productId}
  </select>
  <select id="availableProductIds" resultType="long">
    SELECT product_id FROM mall_store_inventory WHERE store_id = #{storeId} AND available = TRUE
  </select>
  <insert id="upsert" parameterType="com.zioinfo.mall.inventory.MallStoreInventory">
    INSERT INTO mall_store_inventory (store_id, product_id, available, on_hand, updated_by, updated_at)
    VALUES (#{storeId}, #{productId}, COALESCE(#{available},TRUE), COALESCE(#{onHand},0), #{updatedBy}, NOW())
    ON CONFLICT (store_id, product_id) DO UPDATE SET
      available = EXCLUDED.available, on_hand = EXCLUDED.on_hand, updated_by = EXCLUDED.updated_by, updated_at = NOW()
  </insert>
  <update id="setAvailable">
    INSERT INTO mall_store_inventory (store_id, product_id, available, updated_by, updated_at)
    VALUES (#{storeId}, #{productId}, #{available}, #{updatedBy}, NOW())
    ON CONFLICT (store_id, product_id) DO UPDATE SET
      available = #{available}, updated_by = #{updatedBy}, updated_at = NOW()
  </update>
  <update id="adjustOnHand">
    UPDATE mall_store_inventory SET on_hand = GREATEST(COALESCE(on_hand,0) + #{delta}, 0), updated_at = NOW()
    WHERE store_id = #{storeId} AND product_id = #{productId}
  </update>
</mapper>
