<?php
declare(strict_types=1);

/**
 * FATE 使用新手村 store_public 客戶端金鑰格式（與 newbies 相同演算法）。
 * 優先載入 sibling 專案 newbies；否則使用 includes/spa_store_public_client_key_core.php。
 */

require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_path_safe.php';

$spaClientsLib = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'newbies' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'store_public_api_clients.php';
$coreLib = __DIR__ . DIRECTORY_SEPARATOR . 'spa_store_public_client_key_core.php';

if (fate_path_is_file_safe($spaClientsLib)) {
    require_once $spaClientsLib;
} elseif (!function_exists('spa_store_public_client_key_build') && fate_path_is_file_safe($coreLib)) {
    require_once $coreLib;
}

if (!function_exists('fate_spa_store_public_client_key_build')) {
    /**
     * @return array{ok:bool, key?:string, host?:string, site_url?:string, error?:string}
     */
    function fate_spa_store_public_client_key_build(string $siteUrl): array
    {
        if (function_exists('spa_normalize_site_host') && function_exists('spa_store_public_client_key_host_reject_reason')) {
            $host = spa_normalize_site_host($siteUrl);
            if ($host === null) {
                return ['ok' => false, 'error' => '無法解析網站網址，請輸入含網域的完整 URL（例：https://fate.novice.tw/）'];
            }
            $hostReject = spa_store_public_client_key_host_reject_reason($host);
            if ($hostReject !== null) {
                return ['ok' => false, 'error' => $hostReject];
            }
        }

        if (function_exists('spa_store_public_client_key_build')) {
            $r = spa_store_public_client_key_build($siteUrl);
            if (!empty($r['ok']) && function_exists('spa_normalize_site_url')) {
                $r['site_url'] = spa_normalize_site_url($siteUrl);
            }

            return $r;
        }

        return ['ok' => false, 'error' => '無法載入金鑰模組（缺少 newbies 或 includes/spa_store_public_client_key_core.php）'];
    }
}

if (!function_exists('fate_spa_api_key_local_dev_notice')) {
    /** 後台顯示：說明本機／127.x 無法產生金鑰。 */
    function fate_spa_api_key_local_dev_notice(): string
    {
        if (function_exists('spa_store_public_client_key_local_dev_reject_message')) {
            return spa_store_public_client_key_local_dev_reject_message();
        }

        return '本地端網址無法產生或申請 API 金鑰。不可使用 localhost、127.0.0.1、127.x.x.x 等本機或區域 IP。'
            . '請在正式對外網域設定 FATE_PUBLIC_SITE_ORIGIN；本機開發請在正式站產生金鑰後貼入 data/fate_secrets.json。';
    }
}

if (!function_exists('fate_spa_member_site_url_block_reason')) {
    /** 本站對外網址是否可用於產生 API 金鑰；null 表示可接受。 */
    function fate_spa_member_site_url_block_reason(?string $siteUrl = null): ?string
    {
        $siteUrl ??= fate_spa_member_site_url();
        if ($siteUrl === '') {
            return '無法取得站台對外網址，請設定 FATE_PUBLIC_SITE_ORIGIN';
        }
        if (!function_exists('spa_normalize_site_host') || !function_exists('spa_store_public_client_key_host_reject_reason')) {
            return null;
        }
        $host = spa_normalize_site_host($siteUrl);
        if ($host === null) {
            return '無法解析申請網址，請確認 FATE_PUBLIC_SITE_ORIGIN 格式正確';
        }

        return spa_store_public_client_key_host_reject_reason($host);
    }
}

if (!function_exists('fate_spa_member_site_url')) {
    /** FATE 站台對外網址（供產生金鑰與新手村申請比對） */
    function fate_spa_member_site_url(): string
    {
        if (!function_exists('fate_public_site_absolute_base')) {
            require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_member_email.php';
        }
        $origin = fate_public_site_absolute_base()['origin'] ?? '';
        if ($origin !== '' && function_exists('spa_normalize_site_url')) {
            return spa_normalize_site_url($origin) ?? $origin . '/';
        }

        return $origin !== '' ? rtrim($origin, '/') . '/' : '';
    }
}

if (!function_exists('fate_spa_member_apply_url')) {
    function fate_spa_member_apply_url(): string
    {
        $base = defined('FATE_SPA_API_BASE') ? rtrim((string) FATE_SPA_API_BASE, '/') : 'https://spa.novice.tw';
        $memberBase = (string) (getenv('FATE_SPA_MEMBER_BASE') ?: '');
        if ($memberBase !== '' && preg_match('#^https?://#i', $memberBase)) {
            return rtrim($memberBase, '/') . '/s_api_key_apply.php';
        }

        return $base . '/s_api_key_apply.php';
    }
}

if (!function_exists('fate_spa_partners_list_url')) {
    function fate_spa_partners_list_url(): string
    {
        $base = defined('FATE_SPA_API_BASE') ? rtrim((string) FATE_SPA_API_BASE, '/') : 'https://spa.novice.tw';

        return $base . '/store_public_partners.php';
    }
}

if (!function_exists('fate_spa_store_public_status_api_url')) {
    function fate_spa_store_public_status_api_url(): string
    {
        $base = defined('FATE_SPA_API_BASE') ? rtrim((string) FATE_SPA_API_BASE, '/') : 'https://spa.novice.tw';

        return $base . '/api/store_public_client_status.php';
    }
}

if (!function_exists('fate_spa_store_public_client_status_local')) {
    /**
     * 同機 newbies 資料庫直查（無需 HTTP API）。
     *
     * @return array{ok:bool, error?:string, data?:array<string,mixed>, source?:string}
     */
    function fate_spa_store_public_client_status_local(?string $apiKey, ?string $siteUrlOrHost = null): array
    {
        if (!function_exists('spa_store_public_api_client_lookup_by_key')) {
            return ['ok' => false, 'error' => '本機模組未載入'];
        }
        try {
            if (!function_exists('fate_spa_stores_pdo')) {
                require_once __DIR__ . DIRECTORY_SEPARATOR . 'spa_stores_write.php';
            }
            $spaPdo = fate_spa_stores_pdo();
        } catch (Throwable $e) {
            return ['ok' => false, 'error' => '無法連線新手村資料庫'];
        }

        $apiKey = $apiKey !== null ? trim($apiKey) : '';
        if ($apiKey !== '') {
            $data = spa_store_public_api_client_lookup_by_key($spaPdo, $apiKey);
        } elseif ($siteUrlOrHost !== null && trim($siteUrlOrHost) !== '') {
            $data = spa_store_public_api_client_lookup_by_host($spaPdo, $siteUrlOrHost);
        } else {
            return ['ok' => false, 'error' => '無金鑰且無網址可查'];
        }

        if (empty($data['ok'])) {
            return ['ok' => false, 'error' => (string) ($data['error'] ?? '查詢失敗'), 'data' => $data];
        }

        $data['source'] = 'local_db';

        return ['ok' => true, 'data' => $data, 'source' => 'local_db'];
    }
}

if (!function_exists('fate_spa_store_public_client_status_fetch')) {
    /**
     * 查詢金鑰／網域審核狀態：優先 HTTP（spa API），失敗則改本機 newbies 資料庫。
     *
     * @return array{ok:bool, error?:string, http?:int, data?:array<string,mixed>, source?:string}
     */
    function fate_spa_store_public_client_status_fetch(?string $apiKey, ?string $siteUrlOrHost = null): array
    {
        if (!function_exists('fate_spa_http_get_json')) {
            require_once __DIR__ . DIRECTORY_SEPARATOR . 'spa_http.php';
        }

        $base = fate_spa_store_public_status_api_url();
        $apiKey = $apiKey !== null ? trim($apiKey) : '';
        $httpFailed = null;

        if ($apiKey !== '') {
            $resp = fate_spa_http_get_json($base, $apiKey);
        } elseif ($siteUrlOrHost !== null && trim($siteUrlOrHost) !== '') {
            $host = '';
            if (function_exists('spa_normalize_site_host')) {
                $host = spa_normalize_site_host($siteUrlOrHost) ?? '';
            }
            if ($host === '') {
                $host = trim($siteUrlOrHost);
            }
            $resp = fate_spa_http_get_json($base . '?site_host=' . rawurlencode($host), '');
        } else {
            return ['ok' => false, 'error' => '無金鑰且無網址可查'];
        }

        if (!empty($resp['ok'])) {
            $data = $resp['data'] ?? null;
            if (is_array($data) && !empty($data['ok'])) {
                $data['source'] = 'http_api';

                return ['ok' => true, 'http' => (int) ($resp['http'] ?? 200), 'data' => $data, 'source' => 'http_api'];
            }
            $httpFailed = is_array($data) && isset($data['error'])
                ? (string) $data['error']
                : '新手村回覆異常';
        } else {
            $http = (int) ($resp['http'] ?? 0);
            $httpFailed = (string) ($resp['error'] ?? '無法連線新手村');
            if ($http === 404) {
                $httpFailed .= '（請確認新手村已部署 api/store_public_client_status.php）';
            }
        }

        $local = fate_spa_store_public_client_status_local($apiKey !== '' ? $apiKey : null, $siteUrlOrHost);
        if (!empty($local['ok'])) {
            return $local;
        }

        return [
            'ok' => false,
            'error' => $httpFailed ?? (string) ($local['error'] ?? '查詢失敗'),
            'http' => (int) ($resp['http'] ?? 0),
        ];
    }
}

if (!function_exists('fate_spa_status_badge_class')) {
    function fate_spa_status_badge_class(string $status): string
    {
        return match ($status) {
            'pending' => 'spa-status--pending',
            'active' => 'spa-status--active',
            'suspended' => 'spa-status--suspended',
            'revoked' => 'spa-status--revoked',
            default => 'spa-status--unknown',
        };
    }
}
