<?php
/**
 * Steadfast API keys: local file or Firebase RTDB (after idToken + admin check).
 * Uses user idToken REST (?auth=) via kuriyar-firebase-client.php — no service account / bootstrap.local.php.
 * Shared by steadfast-create-order-proxy.php and kuriyar-api.php (require only for steadfast_load_local_config).
 */
require_once __DIR__ . '/kuriyar-firebase-client.php';

/**
 * @return array{api_key: string, secret_key: string, base_url: string}|null
 */
function steadfast_load_local_config() {
    $path = __DIR__ . '/steadfast-config.local.php';
    if (!is_readable($path)) {
        return null;
    }
    $c = include $path;
    if (!is_array($c)) {
        return null;
    }
    $ak = isset($c['api_key']) ? trim((string) $c['api_key']) : '';
    $sk = isset($c['secret_key']) ? trim((string) $c['secret_key']) : '';
    if ($ak === '' || $sk === '' || $ak === 'PASTE_YOUR_API_KEY_HERE' || $sk === 'PASTE_YOUR_SECRET_KEY_HERE') {
        return null;
    }
    $base = isset($c['base_url']) ? rtrim(trim((string) $c['base_url']), '/') : 'https://portal.packzy.com/api/v1';
    return ['api_key' => $ak, 'secret_key' => $sk, 'base_url' => $base];
}

/**
 * Verify admin + read Steadfast keys from RTDB (same paths as dashboard).
 *
 * @return array{api_key: string, secret_key: string, base_url: string}|array{error: string, http?: int}
 */
function steadfast_resolve_keys_from_firebase($clientId, $idToken) {
    $chk = kuriyar_verify_store_admin($clientId, $idToken);
    if (isset($chk['error'])) {
        return $chk;
    }

    $cfgSnap = kuriyar_rtdb_get('clients/' . $clientId . '/siteSettings/steadfastConfig', $idToken);
    if (isset($cfgSnap['error'])) {
        return ['error' => 'Could not read Steadfast settings: ' . $cfgSnap['error'], 'http' => 503];
    }
    $cfg = $cfgSnap['data'] ?? null;
    if (!is_array($cfg)) {
        return ['error' => 'Steadfast credentials not saved in dashboard settings for this store.', 'http' => 503];
    }
    $apiKey = isset($cfg['apiKey']) ? trim((string) $cfg['apiKey']) : '';
    $secretKey = isset($cfg['secretKey']) ? trim((string) $cfg['secretKey']) : '';
    if ($apiKey === '' || $secretKey === '') {
        return ['error' => 'Save API Key and Secret Key in Dashboard → Settings → Steadfast.', 'http' => 503];
    }
    $baseUrl = 'https://portal.packzy.com/api/v1';
    if (!empty($cfg['baseUrl']) && is_string($cfg['baseUrl'])) {
        $t = rtrim(trim((string) $cfg['baseUrl']), '/');
        if ($t !== '') {
            $baseUrl = $t;
        }
    }
    return [
        'api_key' => $apiKey,
        'secret_key' => $secretKey,
        'base_url' => $baseUrl,
    ];
}
