<?php

namespace App\Http\Controllers;

use App\Http\Requests\SelectionSearchSearchRequest;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Mtc\ContentManager\Contracts\PageModel;

class PageController extends Controller
{
    use DispatchesJobs;

    public function index(SelectionSearchSearchRequest $request, PageModel $pageModel): JsonResource
    {
        $perPage = min((int) $request->input('per_page', 15), 200);

        $query = $pageModel->newQuery()
            ->with([
                'primaryMediaUse.media',
                'users',
                'template',
            ])
            ->when($request->input('my-content'), function ($query) {
                $query->whereHas('users', function ($user_query) {
                    $user_query->where('users.id', Auth::id());
                });
            })
            ->withCommentCount()
            ->setSortBy($request->input('sort_by'))
            ->setFilters($request->input('filters') ?? '')
            ->when($request->filled('selections'), fn($query) => $query->setSelections($request->getSelections()))
            ->when(
                $request->filled('search_term'),
                fn($query) => $query
                    ->where(fn($termQuery) => $termQuery->where('slug', 'like', $request->input('search_term') . '%')
                        ->orWhereFullText('search_content', $request->input('search_term')))
            );

        if ($request->withArchived()) {
            $query = $query->withTrashed();
        }

        $pageResource = Config::get('pages.page_list_resource');
        return new $pageResource($query->paginate($perPage));
    }
}
