<?php

namespace App\Http\Controllers;

use App\Services\GlobalSearchService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class GlobalSearchController extends Controller
{
    public function __invoke(Request $request, GlobalSearchService $search): View
    {
        $data = $request->validate([
            'q' => ['nullable','string','max:100'],
        ]);

        $term = trim((string)($data['q'] ?? ''));
        $groups = mb_strlen($term) >= 2 ? $search->search($request->user(), $term) : [];
        $total = collect($groups)->sum(fn (array $group) => count($group['results']));

        return view('global-search.index', compact('term','groups','total'));
    }
}
