<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdatePatientRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('clients.manage') ?? false;
    }

    protected function prepareForValidation(): void
    {
        $c = $this->input('clinical_code');
        if (is_string($c)) {
            $t = strtoupper(trim($c));
            $this->merge(['clinical_code' => $t === '' ? null : $t]);
        }
    }

    public function rules(): array
    {
        return [
            'clinical_code' => [
                'required',
                'string',
                'max:24',
                'regex:/^[A-Z0-9\-]+$/',
                Rule::unique('patients', 'clinical_code')->ignore($this->route('patient')),
            ],
            'name' => ['required', 'string', 'max:255'],
            'species' => ['nullable', 'string', 'max:64'],
            'breed' => ['nullable', 'string', 'max:128'],
            'sex' => ['nullable', 'string', 'max:16'],
            'birth_date' => ['nullable', 'date'],
            'color' => ['nullable', 'string', 'max:64'],
            'microchip' => ['nullable', 'string', 'max:64'],
            'current_weight_kg' => ['nullable', 'numeric', 'min:0', 'max:99999'],
            'notes' => ['nullable', 'string', 'max:10000'],
            'allergies' => ['nullable', 'string', 'max:5000'],
            'sterilized' => ['nullable', 'in:,0,1'],
            'photo' => ['nullable', 'image', 'max:3072'],
            'remove_photo' => ['nullable', 'boolean'],
            'is_active' => ['boolean'],
        ];
    }
}
