<?php

declare(strict_types=1);

namespace App\Http\Controllers\Project;

use App\Http\Controllers\Concerns\AuthorizesProjectAccess;
use App\Http\Controllers\Controller;
use App\Http\Resources\ReportResource;
use App\Models\Project;
use App\Models\Report;
use Illuminate\Http\Request;

class ProjectRationController extends Controller
{
    use AuthorizesProjectAccess;

    public function __invoke(Request $request, Project $project)
    {
        $this->authorizeProjectAccess($project);

        $query = Report::query()
            ->with(['rationIngredients', 'feedingMeals', 'rationWeekly', 'producer', 'items.product', 'project'])
            ->where('project_id', $project->id)
            ->where('type', Report::TYPE_RATION)
            ->where('workflow_status', Report::WORKFLOW_APPROVED);

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

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

        $perPage = min($request->integer('per_page', 15), 50);

        return ReportResource::collection(
            $request->boolean('noPaginate') ? $query->get() : $query->paginate($perPage)
        );
    }
}
