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

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.starry.admin.modules.blindbox.module.entity.BlindBoxRewardEntity;
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 BlindBoxRewardMapper extends BaseMapper<BlindBoxRewardEntity> {

    @Select("SELECT * FROM blind_box_reward WHERE id = #{id} FOR UPDATE")
    BlindBoxRewardEntity lockByIdForUpdate(@Param("id") String id);

    @Update({
            "UPDATE blind_box_reward",
            "SET status = 'USED',",
            "    used_order_id = #{orderId},",
            "    used_clerk_id = #{clerkId},",
            "    used_time = #{usedTime},",
            "    version = version + 1",
            "WHERE id = #{id}",
            "  AND status = 'UNUSED'"
    })
    int markUsed(
            @Param("id") String id,
            @Param("clerkId") String clerkId,
            @Param("orderId") String orderId,
            @Param("usedTime") LocalDateTime usedTime);

    @Select({
            "SELECT * FROM blind_box_reward",
            "WHERE tenant_id = #{tenantId}",
            "  AND customer_id = #{customerId}",
            "  AND deleted = 0",
            "  AND (#{status} IS NULL OR status = #{status})",
            "ORDER BY created_time DESC"
    })
    List<BlindBoxRewardEntity> listByCustomer(
            @Param("tenantId") String tenantId,
            @Param("customerId") String customerId,
            @Param("status") String status);
}
