<?php

namespace App\Modules\Registrar\Epik;

use App\Core\Registrar\AbstractRegistrar;
use Illuminate\Support\Facades\Log;

class Epik extends AbstractRegistrar
{
    /**
     * Epik API base URL — authoritative wrapper requires the `/v2/` version
     * segment (class.epik_wrapper.php:14,43). SIGNATURE is a query param.
     */
    protected string $apiUrl = 'https://usersapiv2.epik.com/v2';

    // -------------------------------------------------------------------------
    //  Configuration
    // -------------------------------------------------------------------------

    public function getConfigFields(): array
    {
        return [
            'api_signature' => [
                'type' => 'password',
                'label' => __('admin/modules.epik_field_api_signature_label'),
                'required' => true,
                'description' => __('admin/modules.epik_field_api_signature_description'),
                'placeholder' => '********',
                'value' => $this->config['api_signature'] ?? '',
            ],
        ];
    }

    public function validateConfig()
    {
        if (empty($this->config['api_signature'])) {
            throw new \Exception(__('admin/modules.epik_config_api_signature_missing'));
        }

        return true;
    }

    // -------------------------------------------------------------------------
    //  API Helper
    // -------------------------------------------------------------------------

    /**
     * Make an API request to the Epik REST API.
     *
     * Transport derived from class.epik_wrapper.php: base `/v2/{action}`,
     * SIGNATURE query param, GET params appended to the query string,
     * POST/PUT/DELETE send JSON body. Failure is signalled by a top-level
     * `errors[]` array of {message, description} — NOT an HTTP status code.
     */
    protected function callApi($endpoint, $method = 'GET', $data = [])
    {
        $signature = $this->config['api_signature'] ?? '';

        $url = rtrim($this->apiUrl, '/') . '/' . ltrim($endpoint, '/');

        $separator = str_contains($url, '?') ? '&' : '?';
        $url .= $separator . 'SIGNATURE=' . urlencode($signature);

        // GET query params are appended to the URL (wrapper:44-46).
        if (strtoupper($method) === 'GET' && ! empty($data)) {
            $url .= '&' . http_build_query($data);
        }

        Log::debug('Epik API request', [
            'endpoint' => $endpoint,
            'method' => $method,
        ]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json',
        ]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));

        if (in_array(strtoupper($method), ['POST', 'PUT', 'DELETE'], true) && ! empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        curl_setopt($ch, CURLOPT_URL, $url);

        $response = curl_exec($ch);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);
        curl_close($ch);

        if ($curlErrno || $response === false) {
            Log::error('Epik: cURL error', ['errno' => $curlErrno, 'error' => $curlError]);

            return $this->errorResponse(
                __('admin/modules.epik_curl_error', ['error' => $curlError ?: 'No response'])
            );
        }

        return $this->parseResponse((string) $response);
    }

    /**
     * Parse a JSON response. Epik reports failure via a top-level `errors[]`
     * array of {message, description} (wrapper:67-71).
     */
    protected function parseResponse(string $response): array
    {
        $decoded = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE || ! is_array($decoded)) {
            Log::error('Epik: Invalid JSON response', ['response' => substr($response, 0, 500)]);

            return $this->errorResponse(__('admin/modules.epik_invalid_response'));
        }

        if (! empty($decoded['errors']) && is_array($decoded['errors'])) {
            $messages = [];
            foreach ($decoded['errors'] as $err) {
                $msg = $err['message'] ?? '';
                if (! empty($err['description'])) {
                    $msg .= ' - ' . $err['description'];
                }
                if ($msg !== '') {
                    $messages[] = $msg;
                }
            }
            $message = implode('; ', $messages) ?: __('admin/modules.epik_api_error');
            Log::warning('Epik: API error', ['message' => $message]);

            return $this->errorResponse($message);
        }

        return [
            'status' => 'success',
            'message' => '',
            'data' => $decoded['data'] ?? [],
            'meta' => $decoded['meta'] ?? [],
        ];
    }

    // -------------------------------------------------------------------------
    //  Response Helpers
    // -------------------------------------------------------------------------

    protected function successResponse(string $message, array $data = []): array
    {
        return [
            'status' => 'success',
            'message' => $message,
            'data' => $data,
        ];
    }

    protected function errorResponse(string $message, array $data = []): array
    {
        return [
            'status' => 'error',
            'message' => $message,
            'data' => $data,
        ];
    }

    // -------------------------------------------------------------------------
    //  Contact / phone helpers (Epik-specific shapes, class.epik.php:172-189)
    // -------------------------------------------------------------------------

    /**
     * Format a phone number as Epik's `+{ccode}.{number}` (class.epik.php:181).
     * Best-effort without the HostBill Utilities helper: if already in
     * `+cc.number` form pass through; otherwise emit `+{digits}` normalized.
     */
    protected function formatPhone(string $phone): string
    {
        $phone = trim($phone);
        if ($phone === '') {
            return '';
        }
        if (preg_match('/^\+\d+\.\d+$/', $phone)) {
            return $phone;
        }
        $hasPlus = str_starts_with($phone, '+');
        $digits = preg_replace('/\D+/', '', $phone);
        if ($digits === '') {
            return '';
        }

        return ($hasPlus ? '+' : '') . $digits;
    }

    /**
     * Build a single Epik contact block from a canonical PRC-969 contact group.
     * When $update is true, keys are R/A/T/B-prefixed for the whois payload
     * (class.epik.php:183-188); otherwise the create-contact keys are emitted.
     */
    protected function epikContact(array $c, string $group, bool $update = false): array
    {
        $name = trim(($c['first_name'] ?? '') . ' ' . ($c['last_name'] ?? ''));
        $phone = $this->formatPhone($c['phone'] ?? '');

        if (! $update) {
            return [
                'name' => $name,
                'companyname' => $c['company'] ?? '',
                'email' => $c['email'] ?? '',
                'address1' => $c['address1'] ?? '',
                'city' => $c['city'] ?? '',
                'state' => $c['state'] ?? '',
                'zipcode' => $c['postcode'] ?? '',
                'country' => $c['country_code'] ?? '',
                'phonenumber' => $phone,
            ];
        }

        $p = strtoupper(substr($group, 0, 1));

        return [
            $p . 'NAME' => $name,
            $p . 'ORGANIZATION' => $c['company'] ?? '',
            $p . 'EMAIL' => $c['email'] ?? '',
            $p . 'ADDRESS' => $c['address1'] ?? '',
            $p . 'CITY' => $c['city'] ?? '',
            $p . 'STATE' => $c['state'] ?? '',
            $p . 'ZIP' => $c['postcode'] ?? '',
            $p . 'COUNTRY' => $c['country_code'] ?? '',
            $p . 'PHONE' => $phone,
            $p . 'COUNTRYCODE' => $c['country_code'] ?? '',
        ];
    }

    /**
     * Extract the TLD-portion of a domain (never from tld_id — PRC-49).
     */
    protected function splitTld(string $domain): string
    {
        return explode('.', $domain, 2)[1] ?? '';
    }

    // -------------------------------------------------------------------------
    //  Domain Registration
    // -------------------------------------------------------------------------

    /**
     * Register a new domain.
     * POST domains/{name}/create — PERIOD/ASSIGNUSERID/CONTACTS/NSES[]/SPECPARAMS[]
     * (class.epik.php:38-62). Register is gated by an availability pre-check.
     */
    public function registerDomain(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            // Availability pre-check gate (class.epik.php:40-43).
            $availability = $this->checkDomainAvailability(['domain' => $domain]);
            if ($availability['status'] !== 'success') {
                return $availability;
            }
            if (empty($availability['data']['available'])) {
                return $this->errorResponse(__('admin/modules.epik_domain_not_available'));
            }

            $years = (int) ($params['period'] ?? $params['years'] ?? 1);

            // PRC-969: registrant contact via canonical helper (single combined block).
            $requestData = [
                'PERIOD' => $years,
                'ASSIGNUSERID' => '0',
                'CONTACTS' => $this->epikContact($this->contact($params, 'registrant'), 'registrant'),
            ];

            // TLD-ext fields → SPECPARAMS[] (class.epik.php:45-49).
            $additional = $params['additional_fields'] ?? [];
            if (is_array($additional)) {
                foreach ($additional as $name => $value) {
                    if ($value === '' || $value === null) {
                        continue;
                    }
                    $requestData['SPECPARAMS'][] = ['name' => $name, 'value' => $value];
                }
            }

            // Nameservers → flat NSES[] (class.epik.php:50-54).
            $nameservers = array_values(array_filter((array) ($params['nameservers'] ?? [])));
            if (! empty($nameservers)) {
                $requestData['NSES'] = $nameservers;
            }

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/create', 'POST', $requestData);

            if ($result['status'] === 'success') {
                Log::info('Epik: Domain registered', ['domain' => $domain]);

                return $this->successResponse(__('admin/modules.epik_register_success'), [
                    'domain' => $domain,
                    'period' => $years,
                    'registered_at' => now()->toISOString(),
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            Log::error('Epik: Register domain error', ['domain' => $domain, 'error' => $e->getMessage()]);

            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Domain Transfer
    // -------------------------------------------------------------------------

    /**
     * Transfer a domain into Epik.
     * POST domains/{name}/transfers_in — AUTHCODE/ASSIGNUSERID/PERIOD
     * (class.epik.php:63-72).
     */
    public function transferDomain(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $years = (int) ($params['period'] ?? $params['years'] ?? 1);

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/transfers_in', 'POST', [
                'AUTHCODE' => $params['epp_code'] ?? $params['authcode'] ?? '',
                'ASSIGNUSERID' => '0',
                'PERIOD' => $years,
            ]);

            if ($result['status'] === 'success') {
                Log::info('Epik: Domain transfer initiated', ['domain' => $domain]);

                return $this->successResponse(__('admin/modules.epik_transfer_success'), [
                    'domain' => $domain,
                    'transfer_started_at' => now()->toISOString(),
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            Log::error('Epik: Transfer domain error', ['domain' => $domain, 'error' => $e->getMessage()]);

            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Domain Renewal
    // -------------------------------------------------------------------------

    /**
     * Renew a domain.
     * PUT domains/{name}/renew — PERIOD (class.epik.php:73-82).
     */
    public function renewDomain(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $years = (int) ($params['period'] ?? $params['years'] ?? 1);

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/renew', 'PUT', [
                'PERIOD' => $years,
            ]);

            if ($result['status'] === 'success') {
                Log::info('Epik: Domain renewed', ['domain' => $domain]);

                return $this->successResponse(__('admin/modules.epik_renew_success'), [
                    'domain' => $domain,
                    'period' => $years,
                    'renewed_at' => now()->toISOString(),
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            Log::error('Epik: Renew domain error', ['domain' => $domain, 'error' => $e->getMessage()]);

            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Nameservers
    // -------------------------------------------------------------------------

    /**
     * Get nameservers.
     * GET domains/{name}/name_servers — NS list is a CSV in data.description
     * when data.name_servers is present (class.epik.php:92-104).
     */
    public function getNameservers(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/name_servers', 'GET');

            if ($result['status'] === 'success') {
                $data = $result['data'] ?? [];
                $nameservers = [];
                if (isset($data['name_servers'])) {
                    $nameservers = array_values(array_filter(array_map(
                        'trim',
                        explode(',', (string) ($data['description'] ?? ''))
                    )));
                }

                return $this->successResponse(__('admin/modules.epik_nameservers_retrieved'), [
                    'domain' => $domain,
                    'nameservers' => $nameservers,
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    /**
     * Set nameservers.
     * PUT domains/{name}/name_servers — payload `nses` is an associative
     * map {ns1:host, ns2:host,...} of non-empty hosts (class.epik.php:105-120).
     */
    public function setNameservers(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $nameservers = array_values(array_filter(array_map(
                'trim',
                (array) ($params['nameservers'] ?? [])
            )));

            $nses = [];
            $n = 1;
            foreach ($nameservers as $ns) {
                $nses['ns' . $n] = $ns;
                $n++;
            }

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/name_servers', 'PUT', [
                'nses' => $nses,
            ]);

            if ($result['status'] === 'success') {
                Log::info('Epik: Nameservers updated', ['domain' => $domain]);

                return $this->successResponse(__('admin/modules.epik_nameservers_updated'), [
                    'domain' => $domain,
                    'nameservers' => $nameservers,
                    'updated_at' => now()->toISOString(),
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Contact Details
    // -------------------------------------------------------------------------

    /**
     * Get contact details.
     * GET domains/{name}/whois — envelope keys ownerContact/adminContact/
     * techContact/billContact, each with a single combined `name`
     * (class.epik.php:121-135).
     */
    public function getContactDetails(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/whois', 'GET');

            if ($result['status'] === 'success') {
                $data = $result['data'] ?? [];
                $map = [
                    'ownerContact' => 'registrant',
                    'adminContact' => 'admin',
                    'techContact' => 'tech',
                    'billContact' => 'billing',
                ];

                $groups = [];
                foreach ($map as $key => $type) {
                    $c = $data[$key] ?? [];
                    if (empty($c)) {
                        continue;
                    }
                    $parts = explode(' ', (string) ($c['name'] ?? ''), 2);
                    $groups[$type] = [
                        'firstname' => $parts[0] ?? '',
                        'lastname' => $parts[1] ?? '',
                        'company' => $c['organization'] ?? '',
                        'address1' => $c['address'] ?? '',
                        'address2' => '',
                        'city' => $c['city'] ?? '',
                        'state' => $c['state'] ?? '',
                        'postal_code' => $c['zip'] ?? '',
                        'country' => $c['country'] ?? '',
                        'phone' => $c['phone'] ?? '',
                        'email' => $c['email'] ?? '',
                    ];
                }

                return [
                    'status' => 'success',
                    'message' => __('admin/modules.epik_contacts_retrieved'),
                    'groups' => $groups,
                ];
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    /**
     * Set contact details.
     * PUT domains/{name}/whois — single flat `update_whois_info_payload`
     * array_merging all 4 R/A/T/B-prefixed groups (class.epik.php:136-149).
     * Per contract #4 the passed-through group keys are canonicalized here.
     */
    public function setContactDetails(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $payload = [];
            foreach (['registrant', 'admin', 'tech', 'billing'] as $group) {
                $payload = array_merge(
                    $payload,
                    $this->epikContact($this->contact($params, $group), $group, true)
                );
            }

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/whois', 'PUT', [
                'update_whois_info_payload' => $payload,
            ]);

            if ($result['status'] === 'success') {
                Log::info('Epik: Contacts updated', ['domain' => $domain]);

                return $this->successResponse(__('admin/modules.epik_contacts_updated'), [
                    'domain' => $domain,
                    'updated_at' => now()->toISOString(),
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Domain Details / Sync
    // -------------------------------------------------------------------------

    /**
     * Get domain details.
     * GET domains/{name}/info — data.domain / data.expiration_date /
     * data.name_servers (space-separated) (class.epik.php:150-171).
     * Epik exposes no lock endpoint, so no lock flag is reported.
     */
    public function getDomainDetails(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/info', 'GET');

            if ($result['status'] === 'success') {
                $data = $result['data'] ?? [];
                $info = $this->mapInfo($data);

                return $this->successResponse(__('admin/modules.epik_domain_info_retrieved'), [
                    'domain' => $domain,
                    'status' => $info['status'],
                    'expires_at' => $info['expires_at'],
                    'nameservers' => $info['nameservers'],
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    /**
     * Sync a domain's registrar-side state.
     * GET domains/{name}/info (class.epik.php:150-171).
     */
    public function syncDomain(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/info', 'GET');

            if ($result['status'] !== 'success') {
                return $result;
            }

            $info = $this->mapInfo($result['data'] ?? []);

            return $this->successResponse(__('admin/modules.epik_sync_success'), [
                'domain' => $domain,
                'status' => $info['status'],
                'expires_at' => $info['expires_at'],
                'nameservers' => $info['nameservers'],
                'synced_at' => now()->toISOString(),
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    /**
     * Poll an in-progress transfer. Epik has no dedicated transfer-status
     * endpoint — presence of data.domain in /info means the domain has landed
     * in the account (transfer complete). Otherwise still pending.
     */
    public function syncDomainTransfer(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/info', 'GET');

            if ($result['status'] !== 'success') {
                // Transfer not yet in the account: treat as still pending.
                return $this->successResponse(__('admin/modules.epik_transfer_sync_pending'), [
                    'domain' => $domain,
                    'completed' => false,
                    'failed' => false,
                    'pending' => true,
                    'synced_at' => now()->toISOString(),
                ]);
            }

            $data = $result['data'] ?? [];
            if (! empty($data['domain'])) {
                $info = $this->mapInfo($data);
                Log::info('Epik: Domain transfer completed', ['domain' => $domain]);

                return $this->successResponse(__('admin/modules.epik_transfer_sync_completed'), [
                    'domain' => $domain,
                    'completed' => true,
                    'failed' => false,
                    'pending' => false,
                    'expires_at' => $info['expires_at'],
                    'synced_at' => now()->toISOString(),
                ]);
            }

            return $this->successResponse(__('admin/modules.epik_transfer_sync_pending'), [
                'domain' => $domain,
                'completed' => false,
                'failed' => false,
                'pending' => true,
                'synced_at' => now()->toISOString(),
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    /**
     * Map an Epik /info response into normalized fields (class.epik.php:158-169).
     */
    protected function mapInfo(array $data): array
    {
        $status = '';
        $expiresAt = '';

        if (! empty($data['domain'])) {
            $status = 'active';
        }
        if (! empty($data['expiration_date'])) {
            $expiresAt = $data['expiration_date'];
            $ts = strtotime((string) $data['expiration_date']);
            if ($ts !== false && $ts < time()) {
                $status = 'expired';
            }
        }

        $nameservers = [];
        if (! empty($data['name_servers'])) {
            $nameservers = array_values(array_filter(array_map(
                'trim',
                explode(' ', (string) $data['name_servers'])
            )));
        }

        return [
            'status' => $status,
            'expires_at' => $expiresAt,
            'nameservers' => $nameservers,
        ];
    }

    // -------------------------------------------------------------------------
    //  EPP Code
    // -------------------------------------------------------------------------

    /**
     * Get the EPP / auth code.
     * GET domains/{name}/authcode → data.auth_code (class.epik.php:83-91).
     */
    public function getEppCode(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/' . rawurlencode($domain) . '/authcode', 'GET');

            if ($result['status'] === 'success') {
                $data = $result['data'] ?? [];

                return $this->successResponse(__('admin/modules.epik_epp_retrieved'), [
                    'domain' => $domain,
                    'epp_code' => $data['auth_code'] ?? '',
                ]);
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Domain Availability
    // -------------------------------------------------------------------------

    /**
     * Check availability.
     * GET domains/check?DOMAINS={name} — response keyed by UPPERCASE(name),
     * with an optional premium block (class.epik.php:190-207).
     */
    public function checkDomainAvailability(array $params)
    {
        $domain = $params['domain'] ?? '';
        if (empty($domain)) {
            return $this->errorResponse(__('admin/modules.epik_domain_required'));
        }

        try {
            $this->validateConfig();

            $result = $this->callApi('domains/check', 'GET', [
                'DOMAINS' => $domain,
            ]);

            if ($result['status'] === 'success') {
                $data = $result['data'] ?? [];
                $key = strtoupper($domain);
                $entry = $data[$key] ?? [];

                $out = [
                    'domain' => $domain,
                    'available' => ! empty($entry['available']),
                    'checked_at' => now()->toISOString(),
                ];

                if (! empty($entry['premium'])) {
                    $out['premium'] = true;
                    $out['premium_pricing'] = [
                        'register' => $entry['price'] ?? null,
                        'renew' => $entry['renewal_price'] ?? null,
                        'transfer' => $entry['transfer_price'] ?? null,
                        'restore' => $entry['restore_price'] ?? null,
                        'currency' => 'USD',
                    ];
                }

                return $this->successResponse(__('admin/modules.epik_availability_checked'), $out);
            }

            return $result;
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    // -------------------------------------------------------------------------
    //  Unsupported operations (no authoritative Epik endpoint in references)
    // -------------------------------------------------------------------------

    /**
     * Epik manages WHOIS privacy at the registrar level (hideContacts=true,
     * class.epik.php:243-250) — there is no privacy-toggle endpoint. Report a
     * no-op success so the client-area privacy panel does not surface an error.
     */
    public function updatePrivacySettings(array $params)
    {
        return $this->successResponse(__('admin/modules.epik_privacy_registrar_managed'), [
            'domain' => $params['domain'] ?? '',
            'registrar_managed' => true,
        ]);
    }

    public function checkDomainSuggestions(array $params)
    {
        return $this->errorResponse(__('admin/modules.epik_suggestions_unsupported'));
    }

    // Child nameservers (glue) are intentionally NOT overridden: Epik's API has
    // no child-NS command. Declaring error-stubs here would make the reflection-
    // based getSupportedFeatures() falsely advertise 'child_nameservers' (an
    // always-erroring UI panel). Inheriting AbstractRegistrar's throwing defaults
    // keeps the capability un-advertised while still rejecting the call cleanly.
}
