<?php

namespace App\Http\Controllers\Ranch;

use App\Http\Controllers\Controller;
use App\Http\Requests\MoveCattlePastureRequest;
use App\Models\Cattle;
use App\Models\CattleLocationMovement;
use App\Services\CattleLocationMovementService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use InvalidArgumentException;

class CattleLocationMovementController extends Controller
{
    public function __construct(
        private readonly CattleLocationMovementService $movementService,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $query = CattleLocationMovement::query()
            ->with(['cattle:id,ear_tag', 'fatteningLot:id,name'])
            ->orderByDesc('moved_at')
            ->orderByDesc('id');

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

        if ($q = trim((string) $request->get('ear_tag', ''))) {
            $query->whereHas('cattle', fn ($b) => $b->where('ear_tag', 'like', '%'.$q.'%'));
        }

        if ($request->filled('from')) {
            $query->whereDate('moved_at', '>=', $request->date('from'));
        }

        if ($request->filled('to')) {
            $query->whereDate('moved_at', '<=', $request->date('to'));
        }

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

        return response()->json(['data' => $query->paginate(25)]);
    }

    public function movePasture(MoveCattlePastureRequest $request, Cattle $cattle): JsonResponse
    {
        $validated = $request->validated();
        $movedAt = isset($validated['moved_at'])
            ? Carbon::parse($validated['moved_at'])
            : Carbon::today();

        try {
            $movement = $this->movementService->moveToPasture(
                $cattle,
                $validated['pasture_id'] ?? null,
                $validated['pasture_location'] ?? null,
                $movedAt,
                $request->user()?->id,
                $validated['notes'] ?? null,
            );
        } catch (InvalidArgumentException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        return response()->json([
            'data' => [
                'movement' => $movement->load('cattle:id,ear_tag'),
                'current_location' => $this->movementService->currentLocation($cattle->fresh()),
            ],
        ], 201);
    }
}
