<?php

namespace App\Http\Controllers\Admin\Ranch;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCattleHealthEventRequest;
use App\Models\Cattle;
use App\Models\CattleHealthEvent;
use App\Models\MaterialType;
use App\Services\CattleHealthEventService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use InvalidArgumentException;

class HealthEventPageController extends Controller
{
    public function __construct(
        private readonly CattleHealthEventService $healthEventService,
    ) {}

    public function index(Request $request): Response
    {
        $query = CattleHealthEvent::query()
            ->with([
                'cattle:id,ear_tag,status',
                'materialType:id,name',
                'user:id,name',
            ])
            ->orderByDesc('event_date');

        if ($request->filled('event_type')) {
            $query->where('event_type', $request->string('event_type'));
        }

        return Inertia::render('Ranch/Health/Index', [
            'events' => $query->paginate(25)->withQueryString(),
            'eventTypes' => config('ranch.health_event_types'),
            'filters' => [
                'event_type' => $request->get('event_type', ''),
            ],
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Ranch/Health/Form', [
            'cattleOptions' => Cattle::query()->active()->orderBy('ear_tag')->get(['id', 'ear_tag']),
            'eventTypes' => config('ranch.health_event_types'),
            'outcomes' => config('ranch.health_outcomes'),
            'materialTypes' => MaterialType::query()
                ->active()
                ->where('category', config('ranch.health.material_category', 'animal_health'))
                ->orderBy('name')
                ->get(['id', 'name', 'unit']),
        ]);
    }

    public function store(StoreCattleHealthEventRequest $request): RedirectResponse
    {
        try {
            $this->healthEventService->record(
                $request->validated(),
                (int) auth()->id()
            );
        } catch (InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage())->withInput();
        }

        return redirect()
            ->route('admin.ranch.health.index')
            ->with('success', 'Evento de salud registrado.');
    }
}
