<?php

namespace App\Http\Requests;

use App\Models\CattleHealthEvent;
use App\Models\MaterialType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    public function rules(): array
    {
        return [
            'ear_tag' => ['required_without:cattle_id', 'string', 'max:64'],
            'cattle_id' => ['required_without:ear_tag', 'integer', 'exists:cattle,id'],
            'event_type' => ['required', Rule::in(array_keys(config('ranch.health_event_types')))],
            'event_date' => ['required', 'date'],
            'title' => ['required', 'string', 'max:200'],
            'product_name' => ['nullable', 'string', 'max:150'],
            'cost' => ['nullable', 'numeric', 'min:0'],
            'outcome' => [
                'nullable',
                Rule::in(array_keys(config('ranch.health_outcomes'))),
                Rule::requiredIf(fn () => $this->input('event_type') === CattleHealthEvent::TYPE_ILLNESS),
            ],
            'notes' => ['nullable', 'string', 'max:2000'],
            'quantity' => ['nullable', 'numeric', 'min:0.001'],
            'material_type_id' => [
                'nullable',
                'integer',
                'exists:material_types,id',
                Rule::requiredIf(function () {
                    $cost = (float) $this->input('cost', 0);

                    return $cost > 0
                        && ! config('ranch.health.auto_material_expense', true)
                        && ! MaterialType::query()
                            ->active()
                            ->where('category', config('ranch.health.material_category', 'animal_health'))
                            ->exists();
                }),
            ],
        ];
    }

    public function messages(): array
    {
        return [
            'outcome.required' => 'Indique el resultado para enfermedades.',
            'material_type_id.required' => 'Seleccione el material de salud para registrar el gasto.',
        ];
    }
}
