<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class OtpVerificationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'otp' => ['required', 'string', 'size:6', 'regex:/^[0-9]{6}$/'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'otp.required' => 'Please enter the verification code.',
            'otp.size' => 'The verification code must be 6 digits.',
            'otp.regex' => 'The verification code must contain only numbers.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Remove any spaces or dashes from OTP
        $otp = preg_replace('/[^0-9]/', '', $this->otp);

        $this->merge([
            'otp' => $otp,
        ]);
    }

    /**
     * Get the OTP code.
     */
    public function getOtp(): string
    {
        return $this->validated()['otp'];
    }
}
