package com.petshop.backend.repository;

import com.petshop.backend.entity.Cart;
import jakarta.persistence.LockModeType;
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.List;
import java.util.Optional;

@Repository
public interface CartRepository extends JpaRepository<Cart, Long> {

    List<Cart> findByUserId(Long userId);

    Optional<Cart> findByUserIdAndCartStatus(Long userId, String cartStatus);

    @Query("SELECT c FROM Cart c WHERE c.user.id = :userId AND c.store.storeId = :storeId AND c.cartStatus = :status")
    Optional<Cart> findActiveCartByUserAndStore(@Param("userId") Long userId,
                                                @Param("storeId") Long storeId,
                                                @Param("status") String status);

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT c FROM Cart c WHERE c.cartId = :id")
    Optional<Cart> findByIdForUpdate(@Param("id") Long id);
}
