<?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
    {
        $search = $request->filled('search_term') ? $request->input('search_term') : null;
        if ($request->input('view_mode') === 'tree') {
            $pages = $pageModel->newQuery()
                ->with(['template', 'descendants'])
                ->setSortBy($request->input('sort_by'))
                ->whereNull('parent_id')
                ->when(
                    $search,
                    fn ($query) => $query->where(fn ($searchQuery) => $searchQuery->searchByTerm($search)
                        ->orWhereHas('descendants', fn ($childQuery) => $childQuery->searchByTerm($search)))
                )
                ->get();

            $pageResource = Config::get('pages.page_tree_resource');
            return new $pageResource($pages);
        }
        $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(
                $search,
                fn ($query) => $query
                    ->where(fn ($termQuery) => $termQuery->where('slug', 'like', $search . '%')
                        ->orWhere('title', 'like', $search . '%')
                        ->orWhereFullText('search_content', $search))
            );

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

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