package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.haha.entity.CouponTemplate;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface CouponTemplateMapper extends BaseMapper<CouponTemplate> {

    @Select("SELECT * FROM t_coupon_template WHERE deleted = 0 ORDER BY create_time DESC")
    List<CouponTemplate> selectAllTemplates();

    @Select("SELECT * FROM t_coupon_template WHERE status = 1 AND deleted = 0 AND remain_count > 0 AND receive_type = 'Collect' AND (valid_type = 2 OR (valid_type = 1 AND valid_end_time >= NOW())) ORDER BY create_time DESC")
    List<CouponTemplate> selectAvailableTemplates();

    @Update("UPDATE t_coupon_template SET remain_count = remain_count - 1, update_time = NOW() WHERE id = #{id} AND remain_count > 0")
    int decreaseRemainCount(@Param("id") Long id);

    @Update("UPDATE t_coupon_template SET remain_count = remain_count - #{count}, update_time = NOW() WHERE id = #{id} AND remain_count >= #{count}")
    int decreaseRemainCount(@Param("id") Long id, @Param("count") int count);

    @Update("UPDATE t_coupon_template SET remain_count = remain_count + 1, update_time = NOW() WHERE id = #{id}")
    int increaseRemainCount(@Param("id") Long id);

    @Update("UPDATE t_coupon_template SET status = #{status}, update_time = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status);

    @Select("SELECT COUNT(*) FROM t_coupon_template WHERE deleted = 0")
    int countTotal();

    @Select("SELECT SUM(remain_count) FROM t_coupon_template WHERE status = 1 AND deleted = 0")
    Long sumRemainCount();
}
