<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Search;

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

final class GroupSearchController extends Controller
{
    public function __construct(private readonly GroupDiscoveryService $groups) {}

    public function __invoke(Request $request): JsonResponse
    {
        $q = trim((string) $request->query('q', ''));
        if (mb_strlen($q) < 2) {
            return response()->json(['data' => []]);
        }

        $perPage = min(max((int) $request->query('per_page', 6), 1), 12);
        $items = array_map(function (array $group): array {
            $group['group_type'] = $group['type'] ?? null;
            $group['type'] = 'group';

            return $group;
        }, $this->groups->searchCards($q, $request->user(), $perPage));

        return response()->json([
            'data' => $items,
        ]);
    }
}