<?php

namespace App\Services;

use App\Models\Cattle;
use App\Models\Pasture;
use InvalidArgumentException;

class PastureService
{
    public function listForCatalog(bool $activeOnly = true): array
    {
        $query = Pasture::query()->orderBy('sort_order')->orderBy('name');

        if ($activeOnly) {
            $query->active();
        }

        return $query->get(['id', 'name', 'code', 'active', 'sort_order'])->all();
    }

    public function applyToCattle(Cattle $cattle, ?int $pastureId, ?string $pastureLocation = null): void
    {
        if ($pastureId !== null) {
            $pasture = Pasture::query()->active()->find($pastureId);
            if (! $pasture) {
                throw new InvalidArgumentException('El potrero/corral seleccionado no existe o está inactivo.');
            }

            $cattle->pasture_id = $pasture->id;
            $cattle->pasture_location = $pasture->name;

            return;
        }

        if ($pastureLocation !== null) {
            $trimmed = trim($pastureLocation);
            $cattle->pasture_location = $trimmed !== '' ? $trimmed : null;
            $cattle->pasture_id = null;

            if ($cattle->pasture_location) {
                $matched = Pasture::query()->active()->where('name', $cattle->pasture_location)->first();
                $cattle->pasture_id = $matched?->id;
            }
        }
    }

    public function resolveLabel(?int $pastureId, ?string $fallback = null): ?string
    {
        if ($pastureId) {
            return Pasture::query()->whereKey($pastureId)->value('name');
        }

        $trimmed = trim((string) $fallback);

        return $trimmed !== '' ? $trimmed : null;
    }
}
