<?php

namespace App\Http\Requests\Concerns;

trait ValidatesOptionalPurchasePayment
{
    use ValidatesSupplierPaymentFields;

    /**
     * @return array<string, array<int, mixed>>
     */
    protected function optionalPurchasePaymentRules(): array
    {
        return [
            'payment' => ['nullable', 'array'],
            'payment.enabled' => ['sometimes', 'boolean'],
            ...collect($this->supplierPaymentFieldRules())
                ->mapWithKeys(function (array $rules, string $key): array {
                    $conditionalRules = collect($rules)
                        ->map(function (mixed $rule): mixed {
                            if ($rule === 'required') {
                                return 'required_if:payment.enabled,true';
                            }

                            return $rule;
                        })
                        ->all();

                    return ["payment.{$key}" => $conditionalRules];
                })
                ->all(),
        ];
    }

    /**
     * @return array<string, mixed>|null
     */
    public function validatedPayment(): ?array
    {
        $payment = $this->input('payment');

        if (! is_array($payment) || empty($payment['enabled'])) {
            return null;
        }

        return [
            'currency' => (string) $payment['currency'],
            'amount' => $payment['amount'],
            'bill_payment_amount' => $payment['bill_payment_amount'] ?? null,
            'paid_at' => (string) $payment['paid_at'],
            'payment_method' => $payment['payment_method'] ?? null,
            'reference' => $payment['reference'] ?? null,
            'notes' => $payment['notes'] ?? null,
            'exchange_rate' => $payment['exchange_rate'] ?? null,
        ];
    }
}
