<?php

namespace App\Support;

class SupplierPaymentAmounts
{
    /**
     * @param  array{
     *     currency: string,
     *     amount: float|int|string,
     *     bill_payment_amount?: float|int|string|null,
     *     exchange_rate?: float|int|string|null,
     * }  $paymentData
     * @return array{
     *     currency: string,
     *     amount: float,
     *     bill_amount: float,
     *     exchange_rate: float|int|string|null,
     * }
     */
    public static function normalizeForStorage(array $paymentData, string $billCurrency): array
    {
        $paymentCurrency = (string) $paymentData['currency'];
        $exchangeRate = $paymentData['exchange_rate'] ?? null;
        $exchangeRateFloat = $exchangeRate !== null && $exchangeRate !== ''
            ? (float) $exchangeRate
            : null;

        if ($paymentCurrency === $billCurrency) {
            $amount = Money::toFloat($paymentData['amount']);

            return [
                'currency' => $paymentCurrency,
                'amount' => $amount,
                'bill_amount' => $amount,
                'exchange_rate' => null,
            ];
        }

        if ($exchangeRateFloat === null || $exchangeRateFloat <= 0) {
            throw new \InvalidArgumentException(__('Exchange rate is required when payment currency differs from the bill.'));
        }

        $billPaymentAmount = $paymentData['bill_payment_amount'] ?? null;

        if ($billPaymentAmount === null || $billPaymentAmount === '') {
            throw new \InvalidArgumentException(
                __('Bill payment amount is required when payment currency differs from the bill.'),
            );
        }

        $billAmount = Money::toFloat($billPaymentAmount);
        $cashAmount = SupplierPaymentExchange::toPaymentCurrency(
            $billAmount,
            $paymentCurrency,
            $billCurrency,
            $exchangeRateFloat,
        );

        return [
            'currency' => $paymentCurrency,
            'amount' => $cashAmount,
            'bill_amount' => $billAmount,
            'exchange_rate' => $exchangeRateFloat,
        ];
    }
}
