<?php

namespace App\Controllers;

use App\Models\DocumentModel;

class ApiController extends BaseController
{
    /** AJAX: search published documents for internal citation picker */
    public function searchDocuments()
    {
        if (! auth()->loggedIn()) {
            return $this->response->setJSON(['error' => 'Unauthorized'])->setStatusCode(401);
        }

        $q       = trim($this->request->getGet('q') ?? '');
        $exclude = (int) ($this->request->getGet('exclude') ?? 0); // current doc id

        if (strlen($q) < 2) {
            return $this->response->setJSON([]);
        }

        $results = model(DocumentModel::class)->searchPublished($q);

        // Remove the current document from results (can't cite yourself)
        if ($exclude > 0) {
            $results = array_filter($results, fn($r) => (int) $r['id'] !== $exclude);
        }

        $results = array_values($results);

        return $this->response->setJSON($results);
    }
}
