<?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\MediaItemResource;
use App\Models\MediaItem;
use App\Models\Project;
use Illuminate\Http\Request;

class ProjectDocumentController extends Controller
{
    use AuthorizesProjectAccess;

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

        $query = MediaItem::query()
            ->with(['category', 'subcategory', 'project'])
            ->where('project_id', $project->id)
            ->where('type', MediaItem::TYPE_DOCUMENT)
            ->where('status', MediaItem::STATUS_APPROVED);

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

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

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

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

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