<?php

namespace App\Http\Controllers\Ranch;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCalvingRequest;
use App\Models\CattleCalvingEvent;
use App\Services\CattleCalvingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use InvalidArgumentException;

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

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

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

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

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

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

    public function store(StoreCalvingRequest $request): JsonResponse
    {
        try {
            $result = $this->calvingService->register(
                $request->validated(),
                $request->user()?->id,
            );
        } catch (InvalidArgumentException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

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