package com.bookshop.structural.adapter;

import com.bookshop.domain.Customer;
import java.math.BigDecimal;

/**
 * Translates between the shop's {@link CardPayments} interface and the legacy gateway's
 * incompatible API. All the ugly conversion lives here -- and nowhere else.
 */
public class LegacyGatewayAdapter implements CardPayments {

    private final LegacyPaymentGateway gateway;

    public LegacyGatewayAdapter(LegacyPaymentGateway gateway) {
        this.gateway = gateway;
    }

    @Override
    public PaymentResult charge(Customer customer, BigDecimal amount) {
        String reference = "CUST/" + customer.id();
        long pence = amount.movePointRight(2).longValueExact();

        int status = gateway.makePayment(reference, pence);
        return switch (status) {
            case LegacyPaymentGateway.STATUS_OK -> PaymentResult.success();
            case LegacyPaymentGateway.STATUS_INSUFFICIENT_FUNDS -> PaymentResult.failure("insufficient funds");
            default -> PaymentResult.failure("gateway error (status " + status + ")");
        };
    }
}
