<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\DocumentsIndex;
use App\Http\Resources\DocumentsCollection;
use App\Models\Document;

class DocumentController extends Controller
{
    public function index(DocumentsIndex $request)
    {
        $data = $request->validated();
        $encrypter = getEncrypter(config("app.lists_key"));
        $pageKey = isset($data['pagekey']) ? $data['pagekey'] : null;
        $searchParams = $data['search'] ?? "";
        $withScientificArticle = (bool)$data['scientific_article'] ?? false;
        $withRecord = (bool)$data['record'] ?? false;
        $nextKeyValue = false;
        $orderFieldName = 'date';
        $orderByDirection = 'desc';
        $orderDirection = '<';
        $query = Document::full();
        if ($searchParams !== "") {
            $q = fulltext_search_term($searchParams, true, false);
            $query->selectRaw('documents.*, document_languages.*, website_objects.*, website_objects_lang.*, MATCH(title, author) AGAINST (? IN BOOLEAN MODE) as score', [$q])
            ->whereRaw('MATCH(title, author) AGAINST (? IN BOOLEAN MODE)', [$q]);
        }

        $query->with([
            'file',
            'themes' => function ($query) {
                $query->full();
            },
        ]);
        if ($withScientificArticle || $withRecord) {
            $query->where(function ($query) use ($withScientificArticle, $withRecord) {
                if ($withScientificArticle) {
                    $query->orWhere('document_type', 'scientific_article');
                }

                if ($withRecord) {
                    $query->orWhere('document_type', 'record');
                }
            });
        }
        $query->orderBy($orderFieldName, $orderByDirection)->orderBy('id', 'DESC');
        if ($pageKey) {
            addNextKeyToQuery($encrypter, $query, $pageKey, $orderFieldName, $orderDirection, 'id');
        }
        $pageSize = 5;
        $query->limit($pageSize + 1); // Check if more pages exist

        // Fetch the query
        $documents = $query->get();
        if ($documents->count() > $pageSize) {
            $documents->pop();
            $hasNextPage = true;
        } else {
            $hasNextPage = false;
        }

        if (!$documents->isEmpty() && $hasNextPage) {
            $nextKeyValue = getNextKeyValue($encrypter, $documents, $orderFieldName, 'id');
        }

        return new DocumentsCollection($documents, $nextKeyValue);
    }
}
