<?php

namespace App\Http\Requests\Api;

use App\Models\PaymentMethod;
use Illuminate\Foundation\Http\FormRequest;

class DepositRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth('client')->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $rules = [
            'gateway' => 'required|string|exists:payment_methods,slug',
            'amount' => 'required|numeric|min:1',
            'currency' => 'required|string|exists:currencies,code',
        ];

        // Defensive null check and lazy loading
        $paymentMethod = PaymentMethod::where('slug', $this->input('gateway'))->first();

        if ($paymentMethod?->type === 'manual' && $paymentMethod->meta && count($paymentMethod->meta) > 0) {
            foreach ($paymentMethod->meta as $key => $value) {
                $rules['fields.'.$key.'.value'] = ($value['required'] ? 'required' : 'nullable').'|'.$this->prepareDynamicFieldTypes($value['field_type']);
                $rules['fields.'.$key.'.label'] = ($value['required'] ? 'required' : 'nullable');
                $rules['fields.'.$key.'.type'] = ($value['required'] ? 'required' : 'nullable');
            }
        }

        return $rules;
    }

    private function prepareDynamicFieldTypes($type)
    {
        if ($type === 'number') {
            return 'numeric';
        } elseif ($type === 'file') {
            return 'mimes:pdf,doc|max:2048';
        } elseif ($type === 'image') {
            return 'image|mimes:jpg,png,jpeg|max:2048';
        }

        return 'string';
    }

    public function messages(): array
    {
        return [
            'gateway.required' => __('The gateway field is required.'),
            'amount.required' => __('The amount field is required.'),
            'amount.numeric' => __('The amount must be a number.'),
            'amount.min' => __('The amount must be at least 1.'),
            'currency.required' => __('The currency field is required.'),
            'currency.exists' => __('The selected currency is invalid.'),
            'fields.*.value.required' => __('Enter the value of the field.'),
        ];
    }
}
