<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

/**
 * SmsTestRequest
 * 
 * Form validation request for SMS testing.
 * Validates test phone number and message before sending test SMS.
 * 
 * @package App\Http\Requests
 */
class SmsTestRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return auth()->check() && auth()->user()->can('manage sms configuration');
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'test_phone' => [
                'required',
                'string',
                'min:9',
                'max:20',
                'regex:/^[\+]?[0-9\-\s]+$/',
            ],
            'test_message' => [
                'nullable',
                'string',
                'max:160',
            ],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'test_phone.required' => 'A test phone number is required.',
            'test_phone.min' => 'The phone number must be at least 9 digits.',
            'test_phone.max' => 'The phone number cannot exceed 20 characters.',
            'test_phone.regex' => 'Please enter a valid phone number.',
            
            'test_message.max' => 'The test message cannot exceed 160 characters.',
        ];
    }

    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'test_phone' => trim($this->test_phone ?? ''),
            'test_message' => trim($this->test_message ?? ''),
        ]);
    }
}
