/*
 * File: src/main/java/purchase/repository/SupplierRepository.java
 * Description: This repository interface provides data access and management capabilities for
 * Supplier entities within the ERP system. Extending JpaRepository, it enables standard
 * CRUD operations and includes a custom query for fetching supplier data filtered by tenant.
*/

package com.nebula.erp.purchase.repository;

import com.nebula.erp.purchase.model.Purchase;
import com.nebula.erp.purchase.model.Supplier;
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 java.util.Optional;

public interface SupplierRepository extends JpaRepository<Supplier, Long> {
    @Query("""
                SELECT s FROM Supplier s
                WHERE s.tenant = :tenant
                ORDER BY s.created_at DESC
            """)
    Page<Supplier> findAllByTenant(
            @Param("tenant") String tenant,
            Pageable pageable);

    @Query("""
                SELECT s FROM Supplier s
                WHERE s.tenant = :tenant
                  AND (
                        LOWER(s.supplier_id) LIKE :keyword
                     OR LOWER(s.supplier_name) LIKE :keyword
                     OR LOWER(s.contact_person) LIKE :keyword
                     OR LOWER(s.phone_number) LIKE :keyword
                     OR LOWER(s.supplier_type) LIKE :keyword
                  )
                ORDER BY s.created_at DESC
            """)
    Page<Supplier> searchSuppliers(
            @Param("tenant") String tenant,
            @Param("keyword") String keyword,
            Pageable pageable);

    @Query("SELECT s FROM Supplier s WHERE s.id = :id AND s.tenant = :tenant")
    Optional<Supplier> findByIdAndTenant(
            @Param("id") Long id,
            @Param("tenant") String tenant);

    @Query("SELECT COUNT(s) FROM Supplier s WHERE s.tenant = :tenant")
    Integer findCountByTenant(@Param("tenant") String tenant);
}