<?php

namespace App\Http\Controllers\Store\Api;

use App\Core\Registrar\AbstractRegistrar;
use App\Core\Registrar\RegistrarManager;
use App\Http\Controllers\Controller;
use App\Models\Tld;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Returns the registrar module's extra field definitions for a given TLD.
 * Consumed by the basket modal to render additional registration inputs.
 */
class DomainExtraFieldsController extends Controller
{
    public function __construct(private RegistrarManager $registrarManager) {}

    public function show(Request $request): JsonResponse
    {
        $tldId = $request->integer('tld_id');
        if ($tldId <= 0) {
            return response()->json(['fields' => []]);
        }

        $tld = Tld::find($tldId);
        if (! $tld || ! $tld->registrar) {
            return response()->json(['fields' => []]);
        }

        $moduleName = strtolower((string) $tld->registrar);
        if (! $this->registrarManager->has($moduleName)) {
            return response()->json(['fields' => []]);
        }

        try {
            $module = $this->registrarManager->get($moduleName);
            if (! $module instanceof AbstractRegistrar) {
                return response()->json(['fields' => []]);
            }
            $fields = $module->getExtraFields(ltrim((string) $tld->tld, '.'));
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::warning(
                'DomainExtraFieldsController: registrar call failed',
                ['module' => $moduleName, 'tld_id' => $tldId, 'error' => $e->getMessage()],
            );
            return response()->json(['fields' => []]);
        }

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