<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class TwoFactorRequest 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 [
            'code' => ['required', 'string', 'size:6', 'regex:/^[0-9]{6}$/'],
        ];
    }

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

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

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

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