<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Tags\PopularTagsRequest;
use App\Http\Requests\Tags\TagSearchRequest;
use App\Services\Tags\TagDiscoveryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;

final class TagController extends Controller
{
    public function __construct(private readonly TagDiscoveryService $tagDiscoveryService) {}

    public function search(TagSearchRequest $request): JsonResponse
    {
        $q = trim((string) ($request->validated()['q'] ?? ''));

        // Short results cached for 2 min; empty-query (popular suggestions) for 5 min.
        $ttl      = $q === '' ? 300 : 120;
        $cacheKey = 'tags.search.v2.' . ($q === '' ? '__empty__' : md5($q));
        $legacyCacheKey = 'tags.search.' . ($q === '' ? '__empty__' : md5($q));

        $data = Cache::remember($cacheKey, $ttl, function () use ($q): mixed {
            return $this->tagDiscoveryService->searchSuggestions($q, 20);
        });

        Cache::put($legacyCacheKey, $data, $ttl);

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

    public function popular(PopularTagsRequest $request): JsonResponse
    {
        $limit    = (int) ($request->validated()['limit'] ?? 20);
        $cacheKey = 'tags.popular.v2.' . $limit;
        $legacyCacheKey = 'tags.popular.' . $limit;

        $data = Cache::remember($cacheKey, 300, function () use ($limit): mixed {
            return $this->tagDiscoveryService->popularTags($limit);
        });

        Cache::put($legacyCacheKey, $data, 300);

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