<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Marketplace;

use App\Http\Resources\TldResource;
use App\Models\Tld;
use App\Services\Marketplace\CatalogueCache;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * Public TLD directory, used to populate search filters and listing forms.
 */
final class TldController extends Controller
{
    public function __construct(
        private readonly CatalogueCache $cache,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $listableOnly = ! $request->boolean('include_unlistable');

        $payload = $this->cache->remember(
            CatalogueCache::tldKey($listableOnly),
            CatalogueCache::TLD_TTL,
            function () use ($listableOnly, $request): array {
                $tlds = Tld::query()
                    ->when($listableOnly, fn ($query) => $query->listable(), fn ($query) => $query->active())
                    ->orderByDesc('is_premium')
                    ->orderBy('sort_order')
                    ->orderBy('tld')
                    ->get();

                return TldResource::collection($tlds)
                    ->response($request)
                    ->getData(assoc: true);
            }
        );

        return response()->json($payload);
    }
}
