package com.toyshop.service;

import com.toyshop.entity.*;
import com.toyshop.repository.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {
  private final CartItemRepository cartItemRepository;
  private final ProductRepository productRepository;

  public CartService(CartItemRepository cartItemRepository, ProductRepository productRepository) {
    this.cartItemRepository = cartItemRepository;
    this.productRepository = productRepository;
  }

  public List<CartItem> list(User user) {
    return cartItemRepository.findByUser(user);
  }

  public void add(User user, Long productId, Integer quantity) {
    Product product = productRepository.findById(productId).orElseThrow();
    CartItem item = cartItemRepository.findByUserAndProduct(user, product)
        .orElseGet(() -> {
          CartItem c = new CartItem();
          c.setUser(user);
          c.setProduct(product);
          c.setQuantity(0);
          return c;
        });
    item.setQuantity(item.getQuantity() + quantity);
    cartItemRepository.save(item);
  }

  public void update(User user, Long itemId, Integer quantity) {
    CartItem item = cartItemRepository.findById(itemId).orElseThrow();
    if (!item.getUser().getId().equals(user.getId())) {
      throw new IllegalArgumentException("无权限");
    }
    item.setQuantity(quantity);
    cartItemRepository.save(item);
  }

  public void remove(User user, Long itemId) {
    CartItem item = cartItemRepository.findById(itemId).orElseThrow();
    if (!item.getUser().getId().equals(user.getId())) {
      throw new IllegalArgumentException("无权限");
    }
    cartItemRepository.delete(item);
  }
}
