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

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.starry.admin.modules.blindbox.module.dto.BlindBoxCandidate;
import com.starry.admin.modules.blindbox.module.entity.BlindBoxPoolEntity;
import java.time.LocalDateTime;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface BlindBoxPoolMapper extends BaseMapper<BlindBoxPoolEntity> {

    @Select({
            "SELECT id AS poolId,",
            "       tenant_id AS tenantId,",
            "       blind_box_id AS blindBoxId,",
            "       reward_gift_id AS rewardGiftId,",
            "       reward_price AS rewardPrice,",
            "       weight,",
            "       remaining_stock AS remainingStock",
            "FROM blind_box_pool",
            "WHERE tenant_id = #{tenantId}",
            "  AND blind_box_id = #{blindBoxId}",
            "  AND status = 1",
            "  AND deleted = 0",
            "  AND (valid_from IS NULL OR valid_from <= #{now})",
            "  AND (valid_to IS NULL OR valid_to >= #{now})",
            "  AND (remaining_stock IS NULL OR remaining_stock > 0)"
    })
    List<BlindBoxCandidate> listActiveEntries(
            @Param("tenantId") String tenantId,
            @Param("blindBoxId") String blindBoxId,
            @Param("now") LocalDateTime now);

    @Update({
            "UPDATE blind_box_pool",
            "SET remaining_stock = CASE",
            "        WHEN remaining_stock IS NULL THEN NULL",
            "        ELSE remaining_stock - 1",
            "    END",
            "WHERE tenant_id = #{tenantId}",
            "  AND id = #{poolId}",
            "  AND reward_gift_id = #{rewardGiftId}",
            "  AND deleted = 0",
            "  AND (remaining_stock IS NULL OR remaining_stock > 0)"
    })
    int consumeRewardStock(
            @Param("tenantId") String tenantId,
            @Param("poolId") Long poolId,
            @Param("rewardGiftId") String rewardGiftId);
}
