package com.petshop.backend.repository;

import com.petshop.backend.entity.Inventory;
import jakarta.persistence.LockModeType;
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.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface InventoryRepository extends JpaRepository<Inventory, Long> {

    @Query("SELECT i FROM Inventory i WHERE i.product.prodId = :productId")
    Optional<Inventory> findByProductId(@Param("productId") Long productId);

    @Query("SELECT i FROM Inventory i WHERE i.product.prodId = :productId AND i.store.storeId = :storeId")
    Optional<Inventory> findByProductIdAndStoreId(@Param("productId") Long productId, @Param("storeId") Long storeId);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT i FROM Inventory i WHERE i.product.prodId = :productId AND i.store.storeId = :storeId")
    Optional<Inventory> findByProductIdAndStoreIdForUpdate(@Param("productId") Long productId, @Param("storeId") Long storeId);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT i FROM Inventory i WHERE i.inventoryId = :id")
    Optional<Inventory> findByIdForUpdate(@Param("id") Long id);

    @Query("SELECT i FROM Inventory i LEFT JOIN i.store s WHERE " +
           "(:q IS NULL OR (" +
           "LOWER(i.product.prodName) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
           "LOWER(i.product.category.categoryName) LIKE LOWER(CONCAT('%', :q, '%')) OR " +
           "LOWER(s.storeName) LIKE LOWER(CONCAT('%', :q, '%')))) AND " +
           "(:storeId IS NULL OR i.store.storeId = :storeId)")
    Page<Inventory> searchInventory(@Param("q") String query, @Param("storeId") Long storeId, Pageable pageable);
}
