package br.gov.sigefp.treasury.repository;

import br.gov.sigefp.treasury.domain.TreasuryEntry;
import br.gov.sigefp.treasury.domain.TreasuryEntryType;
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 TreasuryEntryRepository extends JpaRepository<TreasuryEntry, UUID> {
    
    @Query("SELECT te FROM TreasuryEntry te WHERE te.cashAccount.id = :cashAccountId")
    Page<TreasuryEntry> findByCashAccountId(@Param("cashAccountId") UUID cashAccountId, Pageable pageable);
    
    Page<TreasuryEntry> findByType(TreasuryEntryType type, Pageable pageable);
    
    Page<TreasuryEntry> findByStatus(String status, Pageable pageable);
    
    @Query("SELECT te FROM TreasuryEntry te WHERE te.cashAccount.id = :cashAccountId AND te.type = :type")
    Page<TreasuryEntry> findByCashAccountIdAndType(@Param("cashAccountId") UUID cashAccountId, 
                                                    @Param("type") TreasuryEntryType type, Pageable pageable);
    
    @Query("SELECT te FROM TreasuryEntry te WHERE te.cashAccount.id = :cashAccountId AND te.status = :status")
    Page<TreasuryEntry> findByCashAccountIdAndStatus(@Param("cashAccountId") UUID cashAccountId, 
                                                      @Param("status") String status, Pageable pageable);
    
    @Query("SELECT te FROM TreasuryEntry te WHERE te.paymentOrderId = :paymentOrderId")
    List<TreasuryEntry> findByPaymentOrderId(@Param("paymentOrderId") UUID paymentOrderId);
    
    @Query("SELECT te FROM TreasuryEntry te WHERE te.paymentBatchId = :paymentBatchId")
    List<TreasuryEntry> findByPaymentBatchId(@Param("paymentBatchId") UUID paymentBatchId);
    
    @Query("SELECT te FROM TreasuryEntry te WHERE te.cashAccount.id = :cashAccountId " +
           "AND te.transactionDate BETWEEN :startDate AND :endDate")
    List<TreasuryEntry> findByCashAccountIdAndDateRange(
        @Param("cashAccountId") UUID cashAccountId,
        @Param("startDate") LocalDate startDate,
        @Param("endDate") LocalDate endDate
    );
    
    @Query("SELECT SUM(te.amount) FROM TreasuryEntry te WHERE te.cashAccount.id = :cashAccountId " +
           "AND te.type IN :types AND te.status = 'EXECUTED'")
    java.math.BigDecimal calculateTotalByCashAccountAndTypes(
        @Param("cashAccountId") UUID cashAccountId,
        @Param("types") List<TreasuryEntryType> types
    );
}
