package com.bookshop.structural.facade;

import com.bookshop.domain.Book;
import com.bookshop.domain.Customer;
import java.math.BigDecimal;
import java.util.List;

/**
 * The facade: one call that runs the whole checkout -- stock check, reservation,
 * payment, delivery -- in the right order. Callers never touch the subsystems.
 */
public class CheckoutFacade {

    private final InventoryService inventory;
    private final PaymentService payments;
    private final ShippingService shipping;

    public CheckoutFacade(InventoryService inventory, PaymentService payments, ShippingService shipping) {
        this.inventory = inventory;
        this.payments = payments;
        this.shipping = shipping;
    }

    public CheckoutSummary checkout(Customer customer, List<Book> books, String address) {
        if (!inventory.isInStock(books)) {
            throw new IllegalStateException("one or more books are out of stock");
        }
        inventory.reserve(books);

        BigDecimal total = books.stream().map(Book::price).reduce(BigDecimal.ZERO, BigDecimal::add);
        String transactionId = payments.charge(customer, total);
        String shipmentId = shipping.arrangeDelivery(customer, address);

        return new CheckoutSummary(transactionId, shipmentId, total);
    }
}
