package be.seeseepuff.allowanceplanner.repository;

import be.seeseepuff.allowanceplanner.entity.Allowance;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

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

@Repository
public interface AllowanceRepository extends JpaRepository<Allowance, Integer> {
    List<Allowance> findByUserIdOrderByIdAsc(int userId);

    Optional<Allowance> findByIdAndUserId(int id, int userId);

    int countByIdAndUserId(int id, int userId);

    void deleteByIdAndUserId(int id, int userId);

    @Query("SELECT a FROM Allowance a WHERE a.userId = :userId AND a.weight > 0 ORDER BY (a.target - a.balance) ASC")
    List<Allowance> findByUserIdWithPositiveWeightOrderByRemainingAsc(int userId);

    @Query("SELECT COALESCE(SUM(a.weight), 0) FROM Allowance a WHERE a.userId = :userId AND a.weight > 0")
    double sumPositiveWeights(int userId);
}
