package com.mosquito.project.persistence.repository;

import com.mosquito.project.persistence.entity.LinkClickEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.OffsetDateTime;
import java.util.List;

@Repository
public interface LinkClickRepository extends JpaRepository<LinkClickEntity, Long> {

    List<LinkClickEntity> findByActivityId(Long activityId);

    List<LinkClickEntity> findByActivityIdAndCreatedAtBetween(Long activityId, OffsetDateTime startTime, OffsetDateTime endTime);

    List<LinkClickEntity> findByCode(String code);

    @Query(value = "SELECT l.code, COUNT(*) as cnt, l.inviter_user_id FROM link_clicks l " +
           "WHERE l.activity_id = :activityId " +
           "GROUP BY l.code, l.inviter_user_id " +
           "ORDER BY cnt DESC LIMIT :limit",
           nativeQuery = true)
    List<Object[]> findTopSharedLinksByActivityId(@Param("activityId") Long activityId, @Param("limit") int limit);

    @Query("SELECT COUNT(DISTINCT l.ip) FROM LinkClickEntity l " +
           "WHERE l.activityId = :activityId " +
           "AND l.createdAt BETWEEN :startTime AND :endTime")
    long countUniqueVisitorsByActivityIdAndDateRange(
        @Param("activityId") Long activityId,
        @Param("startTime") OffsetDateTime startTime,
        @Param("endTime") OffsetDateTime endTime
    );

    long countByActivityId(Long activityId);
}

