<?php

namespace App\Http\Requests;

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

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

    public function rules(): array
    {
        return [
            'mother_id' => ['nullable', 'integer', 'exists:cattle,id', 'required_without:mother_ear_tag'],
            'mother_ear_tag' => ['nullable', 'string', 'max:64', 'required_without:mother_id'],
            'ear_tag' => ['nullable', 'string', 'max:64', 'unique:cattle,ear_tag'],
            'ear_tag_type' => ['nullable', Rule::in(array_keys(config('ranch.ear_tag_types')))],
            'gender' => ['required', Rule::in(array_keys(config('ranch.genders')))],
            'breed' => ['nullable', 'string', 'max:120'],
            'calving_date' => ['required', 'date', 'before_or_equal:today'],
            'birth_weight_kg' => ['nullable', 'numeric', 'min:0.01', 'max:200'],
            'pasture_id' => ['nullable', 'integer', 'exists:pastures,id'],
            'pasture_location' => ['nullable', 'string', 'max:120'],
            'notes' => ['nullable', 'string', 'max:2000'],
            'calving_notes' => ['nullable', 'string', 'max:2000'],
        ];
    }

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

    public function messages(): array
    {
        return [
            'mother_id.required_without' => 'Indique la madre por arete o selección.',
            'mother_ear_tag.required_without' => 'Indique el arete de la madre.',
        ];
    }
}
