<?php

namespace App\Http\Requests\Visitor;

use App\Enums\VisitorType;
use App\Http\Requests\BaseRequest;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Validation\Rule;

class UpdateVisitorRequest extends BaseRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['sometimes', 'string', 'max:255'],
            'phone' => ['sometimes', 'string', 'max:20'],
            'email' => ['nullable', 'email', 'max:255'],
            'visitor_type' => ['sometimes', Rule::enum(VisitorType::class)],
            'wing_id' => ['sometimes', 'exists:wings,id'],
            'flat_id' => ['sometimes', 'exists:flats,id'],
            'purpose' => ['sometimes', 'string', 'max:500'],
            'photo' => $this->validateFile('photo'),
            'additional_info' => ['nullable', 'array'],
            'is_recurring' => ['nullable', 'boolean'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'name.string' => 'Visitor name must be a string.',
            'phone.string' => 'Phone number must be a string.',
            'visitor_type.enum' => 'Invalid visitor type selected.',
            'wing_id.exists' => 'Selected wing does not exist.',
            'flat_id.exists' => 'Selected flat does not exist.',
            'purpose.string' => 'Purpose must be a string.',
            'photo.image' => 'Photo must be a valid image file.',
            'photo.max' => 'Photo size cannot exceed 2MB.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('is_recurring')) {
            $this->merge([
                'is_recurring' => filter_var($this->input('is_recurring'), FILTER_VALIDATE_BOOLEAN),
            ]);
        }
    }

}
