<?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.InventoryMapper">
  <select id="findAll" resultType="com.zioinfo.mall.inventory.MallInventory">
    SELECT * FROM mall_inventory
    <where><if test="lowStock != null and lowStock == true">on_hand &lt;= safety_stock</if></where>
    ORDER BY id
  </select>
  <select id="findById" resultType="com.zioinfo.mall.inventory.MallInventory">SELECT * FROM mall_inventory WHERE id = #{id}</select>
  <select id="findBySku" resultType="com.zioinfo.mall.inventory.MallInventory">SELECT * FROM mall_inventory WHERE sku = #{sku}</select>
  <insert id="insert" parameterType="com.zioinfo.mall.inventory.MallInventory" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO mall_inventory (product_id, option_id, sku, on_hand, reserved, safety_stock, erp_sync_status)
    VALUES (#{productId}, #{optionId}, #{sku}, COALESCE(#{onHand},0), COALESCE(#{reserved},0), COALESCE(#{safetyStock},0), COALESCE(#{erpSyncStatus},'NONE'))
  </insert>
  <update id="adjust">UPDATE mall_inventory SET on_hand = GREATEST(COALESCE(on_hand,0) + #{delta}, 0), updated_at = NOW() WHERE id = #{id}</update>
  <update id="setErpSync">
    UPDATE mall_inventory SET erp_sync_status = #{status},
      on_hand = COALESCE(#{onHand}, on_hand), updated_at = NOW() WHERE id = #{id}
  </update>
</mapper>
