<?php

namespace App\Http\Requests\Concerns;

use Illuminate\Validation\Rule;

trait ValidatesCurrencyExchangeInput
{
    /**
     * @return array<string, mixed>
     */
    protected function currencyExchangeFieldRules(bool $requireActiveSaraf = true, ?int $allowSarafId = null): array
    {
        if ($requireActiveSaraf) {
            $sarafRule = Rule::exists('sarafs', 'id')->where(function ($query) use ($allowSarafId): void {
                $query->where(function ($inner) use ($allowSarafId): void {
                    $inner->where('is_active', true);

                    if ($allowSarafId !== null) {
                        $inner->orWhere('id', $allowSarafId);
                    }
                });
            });
        } else {
            $sarafRule = Rule::exists('sarafs', 'id');
        }

        return [
            'saraf_id' => ['required', 'integer', $sarafRule],
            'exchange_date' => ['required', 'date'],
            'total_afn' => ['required', 'numeric', 'gt:0'],
            'dollar_difference_price' => ['required', 'numeric'],
            'dollar_price' => ['required', 'numeric', 'gt:0'],
            'receive_dollar' => ['nullable', 'numeric', 'gte:0'],
        ];
    }

    protected function prepareCurrencyExchangeInput(): void
    {
        if ($this->input('receive_dollar') === '' || $this->input('receive_dollar') === null) {
            $this->merge(['receive_dollar' => null]);
        }
    }

    protected function receiveDollarAmount(array $validated): float
    {
        return round((float) ($validated['receive_dollar'] ?? 0), 2);
    }

    protected function validateCurrencyExchangeRate($validator): void
    {
        $validator->after(function ($validator): void {
            $price = round((float) $this->input('dollar_price', 0), 4);
            $difference = round((float) $this->input('dollar_difference_price', 0), 4);

            if ($price + $difference <= 0) {
                $validator->errors()->add(
                    'dollar_price',
                    __('Dollar price plus difference must be greater than zero.'),
                );
            }
        });
    }
}
