package ru.soune.nocopy.repository;

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 ru.soune.nocopy.entity.referral.Referral;
import java.util.List;

@Repository
public interface ReferralJpaRepository extends JpaRepository<Referral, Long> {
    Referral findByReferralLink(String link);

    Referral findByUserId(Long userId);

    List<Referral> findByInviterId(Long inviterId);

    @Query("SELECT r FROM Referral r WHERE r.inviterId = :inviterId AND r.isActive = true")
    List<Referral> findByInviterIdWhenUserActivated(Long inviterId, Pageable pageable);

    @Query("SELECT r FROM Referral r WHERE r.inviterId = :inviterId")
    List<Referral> findByInviterId(Long inviterId, Pageable pageable);

    @Modifying
    @Query("UPDATE Referral r SET " +
            "r.availableIncome = r.availableIncome + :amount ," +
            "r.totalIncome = r.totalIncome + :amount " +
            "WHERE r.userId = :userId")
    void increaseIncome(@Param("userId") Long userId, @Param("amount") int amount);

    @Modifying
    @Query("UPDATE Referral r SET r.levelId = :newLevelId WHERE r.userId = :userId")
    void updateLevel(@Param("userId") Long userId, @Param("newLevelId") String newLevelId);

    @Modifying
    @Query("UPDATE Referral r SET r.isActive = true WHERE r.userId = :userId")
    void activateUser(@Param("userId") Long userId);

    @Query("SELECT COUNT(r) FROM Referral r WHERE r.inviterId = :userId AND r.isActive = true")
    int countActiveInvitees(@Param("userId") Long userId);

    @Query("SELECT COUNT(r) FROM Referral r WHERE r.inviterId = :userId")
    int countTotalInvitees(@Param("userId") Long userId);

    @Query("SELECT COALESCE(SUM(r.totalIncome), 0) FROM Referral r")
    Long getTotalIncome();

    @Query("SELECT COALESCE(SUM(r.availableIncome), 0) FROM Referral r")
    Long getTotalAvailableIncome();

    @Query("SELECT COALESCE(SUM(r.holdBalance), 0) FROM Referral r")
    Long getTotalHoldBalance();

    @Query("""
        SELECT 
            r.userId,
            r.totalIncome
        FROM Referral r
        WHERE r.totalIncome > 0
    """)
    List<Object[]> getIncomePerUser();
}
