<?php

namespace App\Http\Requests;

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

class UpdateCattleRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $cattleId = $this->route('cattle')?->id ?? $this->route('cattle');

        return [
            'ear_tag' => [
                'nullable',
                'string',
                'max:64',
                Rule::unique('cattle', 'ear_tag')->ignore($cattleId),
            ],
            'ear_tag_type' => ['nullable', Rule::in(array_keys(config('ranch.ear_tag_types')))],
            'pasture_id' => ['nullable', 'integer', 'exists:pastures,id'],
            'pasture_location' => ['nullable', 'string', 'max:120'],
            'notes' => ['nullable', 'string', 'max:2000'],
            'breed' => ['nullable', 'string', 'max:120'],
            'target_min_gdp_kg_per_day' => ['nullable', 'numeric', 'min:0'],
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('ear_tag') && trim((string) $this->input('ear_tag')) === '') {
            $this->merge(['ear_tag' => null]);
        }
    }
}
