package ru.soune.nocopy.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import ru.soune.nocopy.entity.payment.Payment;

import java.util.List;
import java.util.Optional;

@Repository
public interface PaymentRepository extends JpaRepository<Payment, String> {
    Optional<Payment> findByPaymentUuid(String paymentUuid);
    List<Payment> findByUserId(Long userId);

    @Query("""
        SELECT COALESCE(SUM(p.tariff.tokens), 0)
        FROM Payment p
        WHERE p.operationType = 'TOKEN'
          AND p.status = 'SUCCEEDED'
    """)
    Long getTotalTokensBought();

    @Query("""
        SELECT 
            p.user.Id,
            COALESCE(SUM(p.tariff.tokens), 0)
        FROM Payment p
        WHERE p.operationType = 'TOKEN'
          AND p.status = 'SUCCEEDED'
        GROUP BY p.user.Id
    """)
    List<Object[]> getTokensBoughtPerUser();
}
