package com.snack.server.module.product.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.snack.server.module.product.entity.ProductSku;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

/**
 * 商品 SKU Mapper
 */
@Mapper
public interface ProductSkuMapper extends BaseMapper<ProductSku> {

    /**
     * 扣减库存（原子操作，乐观锁兜底）
     * @return 受影响行数；0 表示库存不足
     */
    @Update("UPDATE product_sku SET stock = stock - #{quantity}, sales = sales + #{quantity} " +
            "WHERE id = #{skuId} AND stock >= #{quantity}")
    int decrStock(@Param("skuId") Long skuId, @Param("quantity") Integer quantity);

    /**
     * 释放库存（取消订单时调用）
     */
    @Update("UPDATE product_sku SET stock = stock + #{quantity}, sales = sales - #{quantity} " +
            "WHERE id = #{skuId} AND sales >= #{quantity}")
    int incrStock(@Param("skuId") Long skuId, @Param("quantity") Integer quantity);
}
