package com.honey.honey.repository;

import com.honey.honey.model.PromotionUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Optional;

@Repository
public interface PromotionUserRepository extends JpaRepository<PromotionUser, PromotionUser.PromotionUserId> {

    Optional<PromotionUser> findByPromoIdAndUserId(Integer promoId, Integer userId);

    Page<PromotionUser> findByPromoId(Integer promoId, Pageable pageable);

    Page<PromotionUser> findByPromoIdAndUserId(Integer promoId, Integer userId, Pageable pageable);

    long countByPromoId(Integer promoId);

    @Query("SELECT COUNT(pu) FROM PromotionUser pu WHERE pu.promoId = :promoId AND pu.points > :points")
    long countByPromoIdAndPointsGreaterThan(@Param("promoId") int promoId, @Param("points") java.math.BigDecimal points);

    @Modifying
    @Query("UPDATE PromotionUser pu SET pu.points = :points WHERE pu.promoId = :promoId AND pu.userId = :userId")
    int updatePoints(@Param("promoId") int promoId, @Param("userId") int userId, @Param("points") BigDecimal points);
}
