package com.nebula.erp.product.repository;

import com.nebula.erp.product.model.Fees;
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.math.BigDecimal;
import java.util.Optional;

@Repository
public interface FeesRepository extends JpaRepository<Fees, Long> {
    // Fetch fees by tenant
    @Query("SELECT f FROM Fees f WHERE f.tenant = :tenantName AND (:practitioner_id IS NULL OR f.practitioner_id = :practitioner_id) AND f.tenant IS NOT NULL")
    Page<Fees> findAllByTenant(Pageable pageable, @Param("tenantName") String tenantName, @Param("practitioner_id") String practitioner_id);

    // Custom method to find by id and tenant
    @Query("SELECT f FROM Fees f WHERE f.id = :id AND f.tenant = :tenantName")
    Optional<Fees> findByIdAndTenant(@Param("id") Long id, @Param("tenantName") String tenantName);

    // Check if entry exists
    @Query("SELECT CASE WHEN COUNT(f) > 0 THEN true ELSE false END " +
            "FROM Fees f WHERE f.practitioner_id = :practitioner_id " +
            "AND f.speciality = :speciality " +
            "AND f.location_id = :location_id " +
            "AND f.fees_type_id = :fees_type_id " +
            "AND f.service_category = :service_category " +
            "AND f.measurement = :measurement " +
            "AND f.rate = :rate")
    boolean checkIfExists(
            @Param("practitioner_id") String practitioner_id,
            @Param("speciality") String speciality,
            @Param("location_id") String location_id,
            @Param("fees_type_id") String fees_type_id,
            @Param("service_category") String service_category,
            @Param("measurement") String measurement,
            @Param("rate") BigDecimal rate
    );

    // Check if entry exists excluding the provided id
    @Query("SELECT CASE WHEN COUNT(f) > 0 THEN true ELSE false END " +
            "FROM Fees f WHERE f.practitioner_id = :practitioner_id " +
            "AND f.speciality = :speciality " +
            "AND f.location_id = :location_id " +
            "AND f.fees_type_id = :fees_type_id " +
            "AND f.service_category = :service_category " +
            "AND f.measurement = :measurement " +
            "AND f.rate = :rate " +
            "AND f.id != :id")
    boolean existCheckExcludeId(
            @Param("practitioner_id") String practitioner_id,
            @Param("speciality") String speciality,
            @Param("location_id") String location_id,
            @Param("fees_type_id") String fees_type_id,
            @Param("service_category") String service_category,
            @Param("measurement") String measurement,
            @Param("rate") BigDecimal rate,
            @Param("id") Long id
    );
}