<?php

namespace App\Http\Controllers\Store;

use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * PRC-359 — Knowledgebase / announcement suggestions for the ticket form.
 *
 * Public endpoint (no auth — KB content is public). Abuse is contained by
 * the throttle:60,1 middleware on the route. The whole feature is gated by
 * the `knowledgebase_suggestions` setting (previously a ghost toggle).
 */
class KbSuggestController extends Controller
{
    public function suggest(Request $request): JsonResponse
    {
        // Feature gate — also enforced server-side so a disabled toggle
        // can't be driven via the API even if the JS is bypassed.
        if (! setting('knowledgebase_suggestions', false)) {
            return response()->json(['results' => []]);
        }

        $validated = $request->validate([
            'q' => 'required|string|min:3|max:100',
        ]);

        $q = trim($validated['q']);
        $locale = app()->getLocale();

        // Meili: filter to published KB + announcement only (type/status are
        // configured filterable in config/scout.php). Over-fetch then trim.
        $posts = Post::search($q)
            ->where('status', 'published')
            ->whereIn('type', ['kb_article', 'announcement'])
            ->take(15)
            ->get();

        $results = $posts->take(5)->map(function (Post $post) use ($locale) {
            $slug  = $post->getTranslation('slug', $locale) ?: (string) $post->getAttribute('slug');
            $title = $post->getTranslation('title', $locale) ?: (string) $post->getAttribute('title');
            $excerpt = $post->getTranslation('excerpt', $locale) ?: (string) $post->getAttribute('excerpt');

            $url = $post->type === 'kb_article'
                ? route('knowledgebase.show', $slug)
                : route('announcements.show', $slug);

            return [
                'title'   => $title,
                'excerpt' => Str::limit(strip_tags($excerpt), 160),
                'url'     => $url,
                'type'    => $post->type,
            ];
        })->values();

        return response()->json(['results' => $results]);
    }
}
