<?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 ProjectHealthController extends Controller
{
    use AuthorizesProjectAccess;

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

        $query = Report::query()
            ->with(['items.product', 'producer', 'user', 'consumables', 'invoiceItems'])
            ->where('project_id', $project->id)
            ->where('type', Report::TYPE_HEALTH)
            ->where('workflow_status', Report::WORKFLOW_APPROVED);

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

        if ($request->filled('producer_id')) {
            $query->where('producer_id', $request->integer('producer_id'));
        }

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

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

        if ($request->filled('product_id')) {
            $query->where(function ($scope) use ($request): void {
                $scope->where('product_id', $request->integer('product_id'))
                    ->orWhereHas('items', fn ($items) => $items->where('product_id', $request->integer('product_id')));
            });
        }

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

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