package com.example.demo.services;

import com.example.demo.dao.CartRepository;
import com.example.demo.dao.CustomerRepository;
import com.example.demo.entities.Cart;
import com.example.demo.entities.CartItem;
import com.example.demo.entities.Customer;
import com.example.demo.entities.StatusType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class CheckoutServiceImpl implements CheckoutService {
    
    private CustomerRepository customerRepository;
    private CartRepository cartRepository;
    
    @Autowired
    public CheckoutServiceImpl(CustomerRepository customerRepository, CartRepository cartRepository) {
        this.customerRepository = customerRepository;
        this.cartRepository = cartRepository;
    }
    
    @Override
@Transactional
public PurchaseResponse placeOrder(Purchase purchase) {
    
    // Retrieve Cart info
    Cart cart = purchase.getCart();
    
    // Get Cart items from purchase
    Set<CartItem> cartItems = purchase.getCartItems();
    
    // Validate cart is not empty
    if (cartItems == null || cartItems.isEmpty()) {
        System.out.println("Cart is empty - return error");
        return new PurchaseResponse("ERROR: Cart is empty");
    }
    
    // DEBUG: Check party size BEFORE validation
    System.out.println("Party size from cart BEFORE: " + cart.getPartySize());
    
    // Validate and fix party size BEFORE using it
    if (cart.getPartySize() <= 0) {
        System.out.println("Invalid party size - setting to 1");
        cart.setPartySize(1); // Default to 1 if not provided
    }
    
    // DEBUG: Check party size AFTER validation
    System.out.println("Party size from cart AFTER: " + cart.getPartySize());
    
    // Generate order tracking number
    String orderTrackingNumber = generateOrderTrackingNumber();
    System.out.println("Init Generate tracking number " + orderTrackingNumber);
    cart.setOrderTrackingNumber(orderTrackingNumber);
    
    // Set cart status to ordered
    cart.setStatus(StatusType.ordered);
    
    // Populate cart with cartItems
    cartItems.forEach(item -> cart.add(item));
    
    // Let's Calculate total package price
    BigDecimal totalPrice = BigDecimal.ZERO;
    for (CartItem item : cartItems) {
        // Let's add the vacation price
        if (item.getVacation() != null && item.getVacation().getTravel_price() != null) {
            System.out.println("Adding vacation price: " + item.getVacation().getTravel_price());
            totalPrice = totalPrice.add(item.getVacation().getTravel_price());
        }
        
        // Now let's add the excursions price
        if (item.getExcursions() != null) {
            for (var excursion : item.getExcursions()) {
                if (excursion.getExcursion_price() != null) {
                    System.out.println("Adding excursion price: " + excursion.getExcursion_price());
                    totalPrice = totalPrice.add(excursion.getExcursion_price());
                }
            }
        }
    }
    
    System.out.println("Total price before party size multiply: " + totalPrice);
    System.out.println("Party size: " + cart.getPartySize());
    
    // Let's multiply by party size
    totalPrice = totalPrice.multiply(BigDecimal.valueOf(Math.max(cart.getPartySize(), 1)));
    
    System.out.println("Final total price: " + totalPrice);
    cart.setPackagePrice(totalPrice);
    
    // Populate cart with customer
    Customer customer = purchase.getCustomer();
    customer.add(cart);
    
    // Save to database
    customerRepository.save(customer);
    
    System.out.println("Returning tracking number " + orderTrackingNumber);
    return new PurchaseResponse(orderTrackingNumber);
}
    
    private String generateOrderTrackingNumber() {
        // Generate a random UUID as the order tracking number
        return UUID.randomUUID().toString();
    }
}