package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.haha.entity.UserCoupon;
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.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UserCouponMapper extends BaseMapper<UserCoupon> {

    @Select("SELECT uc.*, ct.coupon_name, ct.coupon_type, ct.min_amount " +
            "FROM t_user_coupon uc " +
            "LEFT JOIN t_coupon_template ct ON uc.template_id = ct.id " +
            "WHERE uc.user_id = #{userId} AND uc.status = #{status} AND uc.valid_end_time >= NOW() " +
            "ORDER BY uc.valid_end_time ASC")
    List<UserCoupon> selectByUserIdAndStatus(@Param("userId") Long userId, @Param("status") Integer status);

    @Select("SELECT COUNT(*) FROM t_user_coupon WHERE template_id = #{templateId} AND user_id = #{userId}")
    int countByTemplateAndUser(@Param("templateId") Long templateId, @Param("userId") Long userId);

    @Select("SELECT uc.*, ct.coupon_name, ct.coupon_type, ct.discount_value, ct.min_amount, ct.max_discount " +
            "FROM t_user_coupon uc " +
            "LEFT JOIN t_coupon_template ct ON uc.template_id = ct.id " +
            "WHERE uc.id = #{id}")
    UserCoupon selectWithTemplate(@Param("id") Long id);

    @Update("UPDATE t_user_coupon SET status = 2, update_time = NOW() WHERE status = 0 AND valid_end_time < #{now}")
    int updateExpiredCoupons(@Param("now") LocalDateTime now);

    @Select("SELECT COUNT(*) FROM t_user_coupon WHERE template_id = #{templateId}")
    int countByTemplateId(@Param("templateId") Long templateId);

    @Select("SELECT COUNT(*) FROM t_user_coupon WHERE template_id = #{templateId} AND status = 1")
    int countUsedByTemplateId(@Param("templateId") Long templateId);

    @Select("SELECT COUNT(*) FROM t_user_coupon WHERE user_id = #{userId} AND status = 0 AND valid_end_time >= #{now}")
    int countAvailableByUserId(@Param("userId") Long userId, @Param("now") LocalDateTime now);
}
