package ru.soune.nocopy.repository;

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 org.springframework.stereotype.Repository;
import ru.soune.nocopy.entity.payout.PayoutRequest;
import ru.soune.nocopy.entity.payout.PayoutRequestStatus;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface PayoutRequestRepository extends JpaRepository<PayoutRequest, Long> {

    List<PayoutRequest> findByUserIdOrderByCreatedAtDesc(Long userId);

    Page<PayoutRequest> findByUserId(Long userId, Pageable pageable);

    Optional<PayoutRequest> findByIdAndUserId(Long id, Long userId);

    @Query("SELECT COALESCE(SUM(pr.amount), 0) FROM PayoutRequest pr " +
            "WHERE pr.user.Id = :userId AND pr.status = 'COMPLETED'")
    BigDecimal getTotalPayoutAmountByUser(@Param("userId") Long userId);

    boolean existsByUserIdAndStatusIn(Long userId, List<PayoutRequestStatus> statuses);

    List<PayoutRequest> findByStatusOrderByCreatedAtAsc(PayoutRequestStatus status);

    Page<PayoutRequest> findByStatus(PayoutRequestStatus status, Pageable pageable);

    @Query("SELECT pr FROM PayoutRequest pr WHERE pr.status = 'PENDING' " +
            "AND pr.createdAt < :threshold")
    List<PayoutRequest> findPendingOlderThan(@Param("threshold") LocalDateTime threshold);
}
