<?php

namespace App\Http\Controllers\Admin\Ranch;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCalvingRequest;
use App\Models\Cattle;
use App\Models\CattleCalvingEvent;
use App\Models\Pasture;
use App\Services\CattleCalvingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use InvalidArgumentException;

class CalvingPageController extends Controller
{
    public function __construct(
        private readonly CattleCalvingService $calvingService,
    ) {}

    public function index(Request $request): Response
    {
        $query = CattleCalvingEvent::query()
            ->with(['mother:id,ear_tag,breed', 'calf:id,ear_tag,gender,breed,status'])
            ->orderByDesc('calving_date')
            ->orderByDesc('id');

        return Inertia::render('Ranch/Calvings/Index', [
            'calvings' => $query->paginate(20)->withQueryString(),
            'genders' => config('ranch.genders'),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Ranch/Calvings/Form', [
            'mothers' => Cattle::query()->active()->where('gender', 'female')->orderBy('ear_tag')->get(['id', 'ear_tag', 'breed']),
            'pastures' => Pasture::query()->active()->orderBy('name')->get(['id', 'name']),
            'genders' => config('ranch.genders'),
            'earTagTypes' => config('ranch.ear_tag_types'),
        ]);
    }

    public function store(StoreCalvingRequest $request): RedirectResponse
    {
        try {
            $result = $this->calvingService->register(
                $request->validated(),
                $request->user()?->id,
            );
        } catch (InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage())->withInput();
        }

        return redirect()
            ->route('admin.ranch.cattle.show', $result['calf'])
            ->with('success', 'Parto registrado. Cría agregada al inventario.');
    }
}
