package br.gov.sigefp.budget.repository;

import br.gov.sigefp.budget.domain.BudgetAllocation;
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.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Repository
public interface BudgetAllocationRepository extends JpaRepository<BudgetAllocation, UUID> {
    
    List<BudgetAllocation> findByBudgetLineId(UUID budgetLineId);
    
    @Query("SELECT ba FROM BudgetAllocation ba WHERE ba.budgetLine.id = :budgetLineId ORDER BY ba.createdAt DESC")
    Optional<BudgetAllocation> findLatestByBudgetLineId(@Param("budgetLineId") UUID budgetLineId);
    
    @Query("SELECT COALESCE(SUM(ba.initialAmount + ba.adjustmentAmount), 0) FROM BudgetAllocation ba WHERE ba.budgetLine.id = :budgetLineId")
    BigDecimal calculateTotalAllocatedByBudgetLineId(@Param("budgetLineId") UUID budgetLineId);
}

