package com.starry.admin.modules.shop.mapper;

import com.github.yulichang.base.MPJBaseMapper;
import com.starry.admin.modules.shop.module.entity.PlayCouponInfoEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * 优惠券信息Mapper接口
 */
@Mapper
public interface PlayCouponInfoMapper extends MPJBaseMapper<PlayCouponInfoEntity> {

    @Update({
            "UPDATE play_coupon_info",
            "SET issued_quantity = IFNULL(issued_quantity, 0) + 1,",
            "    remaining_quantity = CASE",
            "        WHEN remaining_quantity IS NULL THEN NULL",
            "        WHEN remaining_quantity < 0 THEN remaining_quantity",
            "        ELSE remaining_quantity - 1",
            "    END",
            "WHERE id = #{id}",
            "  AND (remaining_quantity IS NULL OR remaining_quantity <> 0)"
    })
    int increaseIssuedAndConsumeRemaining(String id);

    @Select({
            "SELECT * FROM play_coupon_info",
            "WHERE id = #{id}",
            "FOR UPDATE"
    })
    PlayCouponInfoEntity selectByIdForUpdate(String id);
}
