<?php

namespace App\Http\Controllers\Ranch;

use App\Http\Controllers\Controller;
use App\Models\Pasture;
use App\Services\PastureService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PastureController extends Controller
{
    public function __construct(
        private readonly PastureService $pastureService,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $query = Pasture::query()->withCount(['cattle as active_cattle_count' => function ($q) {
            $q->where('status', 'active');
        }]);

        if ($request->boolean('active_only', false)) {
            $query->active();
        }

        return response()->json([
            'data' => $query->orderBy('sort_order')->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120', 'unique:pastures,name'],
            'code' => ['nullable', 'string', 'max:40', 'unique:pastures,code'],
            'notes' => ['nullable', 'string'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $pasture = Pasture::create($validated + ['active' => true]);

        return response()->json(['data' => $pasture], 201);
    }

    public function update(Request $request, Pasture $pasture): JsonResponse
    {
        $validated = $request->validate([
            'name' => ['sometimes', 'string', 'max:120', Rule::unique('pastures', 'name')->ignore($pasture->id)],
            'code' => ['nullable', 'string', 'max:40', Rule::unique('pastures', 'code')->ignore($pasture->id)],
            'active' => ['sometimes', 'boolean'],
            'notes' => ['nullable', 'string'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $oldName = $pasture->name;
        $pasture->update($validated);

        if (isset($validated['name']) && $validated['name'] !== $oldName) {
            $pasture->cattle()->update(['pasture_location' => $pasture->name]);
        }

        return response()->json(['data' => $pasture->fresh()]);
    }
}
