package br.gov.sigefp.budget.repository;

import br.gov.sigefp.budget.domain.BudgetLine;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface BudgetLineRepository extends JpaRepository<BudgetLine, UUID>, JpaSpecificationExecutor<BudgetLine> {

    Optional<BudgetLine> findByCode(String code);

    boolean existsByCode(String code);

    @Query("SELECT bl FROM BudgetLine bl WHERE bl.fiscalYear.id = :fiscalYearId AND bl.code = :code")
    Optional<BudgetLine> findByFiscalYearIdAndCode(@Param("fiscalYearId") UUID fiscalYearId,
            @Param("code") String code);

    @Query("SELECT COUNT(bl) > 0 FROM BudgetLine bl WHERE bl.fiscalYear.id = :fiscalYearId AND bl.code = :code")
    boolean existsByFiscalYearIdAndCode(@Param("fiscalYearId") UUID fiscalYearId, @Param("code") String code);

    List<BudgetLine> findByFiscalYearId(UUID fiscalYearId);

    @Query("SELECT bl FROM BudgetLine bl WHERE bl.fiscalYear.id = :fiscalYearId AND bl.ministry = :ministryId")
    List<BudgetLine> findByFiscalYearIdAndMinistryId(@Param("fiscalYearId") UUID fiscalYearId,
            @Param("ministryId") UUID ministryId);

    @Query("SELECT bl FROM BudgetLine bl WHERE bl.fiscalYear.id = :fiscalYearId AND bl.orgUnit = :orgUnitId")
    List<BudgetLine> findByFiscalYearIdAndOrgUnitId(@Param("fiscalYearId") UUID fiscalYearId,
            @Param("orgUnitId") UUID orgUnitId);
}
