<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class SendOtpRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    /**
     * @return array<string, array<int, string>>
     */
    public function rules(): array
    {
        return [
            'phone' => ['required', 'regex:/^\+993 [67]\d \d{2} \d{2} \d{2}$/'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'phone.regex' => 'Telefon belgiňiz şu formatda bolmaly: +993 KX XX XX XX (bu ýerde K 6 ýa-da 7).',
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }

            if (unmask_phone($this->string('phone')->toString()) === '') {
                $validator->errors()->add('phone', 'Telefon belgiňiz şu formatda bolmaly: +993 KX XX XX XX (bu ýerde K 6 ýa-da 7).');
            }
        });
    }

    public function unmaskedPhone(): string
    {
        return unmask_phone($this->string('phone')->toString());
    }
}
