<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Services\SearchService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function __construct(private SearchService $search)
    {
    }

    public function search(Request $request): JsonResponse
    {
        $q = (string) $request->query('q', '');
        $type = $request->query('type');
        $limit = min(50, (int) $request->query('limit', 10));
        $result = $this->search->search($q, $type ?: null, $limit);
        return response()->json(['data' => $result]);
    }

    public function suggest(Request $request): JsonResponse
    {
        $q = (string) $request->query('q', '');
        $result = $this->search->search($q, null, 5);
        $suggestions = [];
        foreach ($result['groups'] as $group => $payload) {
            foreach ($payload['items'] as $item) {
                $suggestions[] = [
                    'group' => $group,
                    'title' => $item['title'],
                    'id' => $item['id'],
                    'slug' => $item['slug'] ?? null,
                ];
            }
        }
        return response()->json(['data' => array_slice($suggestions, 0, 10)]);
    }
}
