<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Helpers\DataNormalizationHelper;

class UpdateWithdrawalRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $withdrawal = $this->route('withdrawal');
        if (!$withdrawal) {
            return false;
        }
        return auth()->check() && auth()->id() == $withdrawal->user_id;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'amount' => 'required|numeric|min:5000|max:9999999',
            'withdrawal_method' => 'required|in:bank_transfer,mobile_money,check',
            'bank_name' => 'required_if:withdrawal_method,bank_transfer|string|max:100',
            'account_number' => 'required_if:withdrawal_method,bank_transfer|string|max:50',
            'account_holder' => 'required_if:withdrawal_method,bank_transfer|string|max:100',
            'mobile_number' => 'required_if:withdrawal_method,mobile_money|string|min:9|max:20',
            'notes' => 'nullable|string|max:500',
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'amount.required' => __('messages.validation.amount_required'),
            'amount.numeric' => __('messages.validation.amount_numeric'),
            'amount.min' => __('messages.validation.amount_min_withdrawal'),
            'withdrawal_method.required' => __('messages.validation.method_required'),
            'withdrawal_method.in' => __('messages.validation.method_invalid'),
            'bank_name.required_if' => __('messages.validation.bank_name_required'),
            'account_number.required_if' => __('messages.validation.account_required'),
            'mobile_number.required_if' => __('messages.validation.mobile_required'),
        ];
    }

    /**
     * Prepare the data for validation.
     * Apply normalization before validation rules.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->merge([
            'amount' => DataNormalizationHelper::normalizeAmount($this->amount ?? 0),
            'mobile_number' => DataNormalizationHelper::normalizePhone($this->mobile_number ?? ''),
            'withdrawal_method' => strtolower($this->withdrawal_method ?? ''),
        ]);
    }
}
