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

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'name.required' => 'Visitor name is required.',
            'phone.required' => 'Phone number is required.',
            'visitor_type.required' => 'Visitor type is required.',
            'wing_id.required' => 'Wing selection is required.',
            'flat_id.required' => 'Flat selection is required.',
            'purpose.required' => 'Purpose of visit is required.',
            '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),
            ]);
        }
    }

}
