<?php

namespace App\Http\Controllers\Admin\Ranch;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreWeightRecordRequest;
use App\Models\Cattle;
use App\Models\WeightRecord;
use App\Services\WeightRecordService;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class WeightRecordPageController extends Controller
{
    public function __construct(
        private readonly WeightRecordService $weightRecordService,
    ) {}

    public function index(Request $request): Response
    {
        $query = WeightRecord::query()
            ->with(['cattle:id,ear_tag,breed', 'user:id,name'])
            ->orderByDesc('weighed_at');

        if ($request->filled('cattle_id')) {
            $query->where('cattle_id', $request->integer('cattle_id'));
        }

        return Inertia::render('Ranch/Weights/Index', [
            'records' => $query->paginate(25)->withQueryString(),
            'filters' => [
                'cattle_id' => $request->get('cattle_id'),
            ],
        ]);
    }

    public function create(Request $request): Response
    {
        return Inertia::render('Ranch/Weights/Form', [
            'cattleOptions' => Cattle::query()->active()->orderBy('ear_tag')->get(['id', 'ear_tag', 'breed']),
            'prefillCattleId' => $request->integer('cattle_id') ?: null,
        ]);
    }

    public function store(StoreWeightRecordRequest $request): RedirectResponse
    {
        $cattle = $request->filled('cattle_id')
            ? Cattle::findOrFail($request->integer('cattle_id'))
            : Cattle::where('ear_tag', $request->string('ear_tag'))->first();

        if (! $cattle) {
            return back()->with('error', 'Animal no encontrado.')->withInput();
        }

        if (! $cattle->isActive()) {
            return back()->with('error', 'El animal no está activo.')->withInput();
        }

        $this->weightRecordService->record(
            $cattle,
            (float) $request->input('weight_kg'),
            Carbon::parse($request->input('weighed_at')),
            $request->input('notes'),
            (int) auth()->id()
        );

        return redirect()
            ->route('admin.ranch.weights.index')
            ->with('success', 'Pesaje registrado.');
    }
}
