package com.mosquito.project.persistence.repository;

import com.mosquito.project.persistence.entity.UserInviteEntity;
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.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserInviteRepository extends JpaRepository<UserInviteEntity, Long> {
    List<UserInviteEntity> findByActivityId(Long activityId);
    List<UserInviteEntity> findByActivityIdAndInviterUserId(Long activityId, Long inviterUserId);
    List<UserInviteEntity> findByInviteeUserId(Long inviteeUserId);

    // 分页查询活动参与者
    Page<UserInviteEntity> findByActivityId(Long activityId, Pageable pageable);

    Page<UserInviteEntity> findByEmailContaining(String email, Pageable pageable);
    Page<UserInviteEntity> findByStatus(String status, Pageable pageable);

    @Query("SELECT u.inviterUserId as userId, COUNT(u) as inviteCount " +
           "FROM UserInviteEntity u " +
           "WHERE u.activityId = :activityId " +
           "GROUP BY u.inviterUserId " +
           "ORDER BY inviteCount DESC")
    List<Object[]> countInvitesByActivityIdGroupByInviter(@Param("activityId") Long activityId);

    @Query("SELECT COUNT(u) FROM UserInviteEntity u WHERE u.activityId = :activityId")
    long countByActivityId(@Param("activityId") Long activityId);

    /**
     * 获取去重的邀请者数量（参与邀请活动的用户数）
     */
    @Query("SELECT COUNT(DISTINCT u.inviterUserId) FROM UserInviteEntity u WHERE u.inviterUserId IS NOT NULL")
    long countDistinctInviters();

    /**
     * 分页查询活动参与者（支持按邮箱或用户ID搜索）
     * 查询条件：email包含query或inviterUserId/inviteeUserId匹配query
     */
    @Query("SELECT u FROM UserInviteEntity u WHERE u.activityId = :activityId " +
           "AND (u.email LIKE %:query% OR CAST(u.inviterUserId AS string) LIKE %:query% OR CAST(u.inviteeUserId AS string) LIKE %:query%)")
    Page<UserInviteEntity> findByActivityIdAndQuery(@Param("activityId") Long activityId, @Param("query") String query, Pageable pageable);
}

