<?php

namespace App\Http\Requests;

use App\Http\Requests\Concerns\ValidatesCurrencyExchangeInput;
use App\Support\CurrencyExchangeCalculator;
use Illuminate\Foundation\Http\FormRequest;

class StoreCurrencyExchangeRequest extends FormRequest
{
    use ValidatesCurrencyExchangeInput;

    public function authorize(): bool
    {
        return $this->user()?->can('sarafs.create') === true;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return $this->currencyExchangeFieldRules();
    }

    protected function prepareForValidation(): void
    {
        $this->prepareCurrencyExchangeInput();
    }

    public function withValidator($validator): void
    {
        $this->validateCurrencyExchangeRate($validator);
    }

    /**
     * @return array<string, mixed>
     */
    public function validated($key = null, $default = null): array
    {
        $validated = parent::validated($key, $default);

        $receiveDollar = $this->receiveDollarAmount($validated);

        $totals = CurrencyExchangeCalculator::calculate(
            round((float) $validated['total_afn'], 2),
            round((float) $validated['dollar_price'], 4),
            round((float) $validated['dollar_difference_price'], 4),
            $receiveDollar,
        );

        return [
            ...$validated,
            'total_afn' => round((float) $validated['total_afn'], 2),
            'dollar_difference_price' => round((float) $validated['dollar_difference_price'], 4),
            'dollar_price' => round((float) $validated['dollar_price'], 4),
            'receive_dollar' => $receiveDollar,
            'total_dollar' => $totals['total_dollar'],
            'remain_dollar_on_saraf' => $totals['remain_dollar_on_saraf'],
        ];
    }
}
