<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    protected function prepareForValidation(): void
    {
        $normalizedBvn = preg_replace('/\D+/', '', (string) $this->input('bvn', ''));
        $normalizedPhone = preg_replace('/\D+/', '', (string) $this->input('phone', ''));

        $this->merge([
            'bvn' => $normalizedBvn !== '' ? $normalizedBvn : null,
            'phone' => $normalizedPhone !== '' ? $normalizedPhone : null,
        ]);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
            'phone' => ['required', 'string', 'digits_between:10,15', Rule::unique(User::class, 'phone')->ignore($this->user()->id)],
            'bvn' => ['nullable', 'digits:11'],
        ];
    }
}
