package de.cannamanage.service.repository;

import de.cannamanage.domain.entity.Payment;
import de.cannamanage.domain.enums.PaymentStatus;
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 java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@Repository
public interface PaymentRepository extends JpaRepository<Payment, UUID> {

    List<Payment> findByClubIdAndMemberId(UUID clubId, UUID memberId);

    Page<Payment> findByClubId(UUID clubId, Pageable pageable);

    Page<Payment> findByClubIdAndMemberId(UUID clubId, UUID memberId, Pageable pageable);

    Page<Payment> findByClubIdAndStatus(UUID clubId, PaymentStatus status, Pageable pageable);

    @Query("SELECT p FROM Payment p WHERE p.clubId = :clubId AND p.memberId = :memberId " +
           "AND p.status = 'PAID' AND p.periodFrom >= :from AND p.periodTo <= :to")
    List<Payment> findPaidByMemberAndPeriod(@Param("clubId") UUID clubId,
                                            @Param("memberId") UUID memberId,
                                            @Param("from") LocalDate from,
                                            @Param("to") LocalDate to);

    @Query("SELECT COALESCE(SUM(p.amountCents), 0) FROM Payment p " +
           "WHERE p.clubId = :clubId AND p.status = 'PAID' " +
           "AND p.periodFrom >= :from AND p.periodTo <= :to")
    Long sumByClubIdAndPeriod(@Param("clubId") UUID clubId,
                              @Param("from") LocalDate from,
                              @Param("to") LocalDate to);

    @Query("SELECT COALESCE(SUM(p.amountCents), 0) FROM Payment p " +
           "WHERE p.clubId = :clubId AND p.memberId = :memberId AND p.status = 'PAID'")
    Long sumPaidByMember(@Param("clubId") UUID clubId, @Param("memberId") UUID memberId);
}
