package com.toyshop.service;

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

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@Service
public class OrderService {
  private final OrderRepository orderRepository;
  private final OrderItemRepository orderItemRepository;
  private final CartItemRepository cartItemRepository;
  private final AddressRepository addressRepository;

  public OrderService(OrderRepository orderRepository, OrderItemRepository orderItemRepository,
                      CartItemRepository cartItemRepository, AddressRepository addressRepository) {
    this.orderRepository = orderRepository;
    this.orderItemRepository = orderItemRepository;
    this.cartItemRepository = cartItemRepository;
    this.addressRepository = addressRepository;
  }

  @Transactional
  public Order createOrder(User user, Long addressId) {
    Address address = addressRepository.findById(addressId).orElseThrow();
    if (!address.getUser().getId().equals(user.getId())) {
      throw new IllegalArgumentException("无权限");
    }
    List<CartItem> cartItems = cartItemRepository.findByUser(user);
    if (cartItems.isEmpty()) {
      throw new IllegalArgumentException("购物车为空");
    }
    BigDecimal total = BigDecimal.ZERO;
    for (CartItem item : cartItems) {
      BigDecimal line = item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
      total = total.add(line);
    }
    Order order = new Order();
    order.setOrderNo("T" + UUID.randomUUID().toString().replace("-", "").substring(0, 16));
    order.setUser(user);
    order.setTotalAmount(total);
    order.setReceiverName(address.getReceiverName());
    order.setReceiverPhone(address.getReceiverPhone());
    order.setReceiverAddress(address.getDetail());
    order.setStatus(OrderStatus.PENDING_PAYMENT);
    orderRepository.save(order);

    for (CartItem item : cartItems) {
      OrderItem orderItem = new OrderItem();
      orderItem.setOrder(order);
      orderItem.setProduct(item.getProduct());
      orderItem.setQuantity(item.getQuantity());
      orderItem.setPrice(item.getProduct().getPrice());
      orderItemRepository.save(orderItem);
    }
    cartItemRepository.deleteByUser(user);
    return order;
  }

  public List<Order> listOrders(User user) {
    return orderRepository.findByUserOrderByCreatedAtDesc(user);
  }
}
