<?php
declare(strict_types=1);

/**
 * Fast storefront bootstrap: siteSettings + up to N newest products (by createdAt).
 * Used by shop-core.js for instantHome preview (reduces skeleton time).
 *
 * Query: clientId=... (required for browser calls) OR site=... (subdomain; resolves via publicSiteMappings).
 * Requires api/firebase-admin-bootstrap.local.php + service account JSON (same as other admin APIs).
 */

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

require_once __DIR__ . '/firebase-rtdb-admin.php';

const HOME_PREVIEW_PRODUCT_CAP = 10;

function sb_json_fail(int $code, string $key, string $message = ''): void {
    http_response_code($code);
    echo json_encode([
        'ok' => false,
        'error' => $key,
        'message' => $message,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function sb_normalize_client_id(string $id): string {
    $id = trim($id);
    if ($id === '') {
        return '';
    }
    if (!preg_match('/^[-a-zA-Z0-9_]{4,128}$/', $id)) {
        return '';
    }
    return $id;
}

function sb_normalize_site_key(string $site): string {
    $site = trim($site);
    if ($site === '') {
        return '';
    }
    if (!preg_match('/^[a-zA-Z0-9][-a-zA-Z0-9_.]{0,62}$/', $site)) {
        return '';
    }
    return $site;
}

$bootstrapPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootstrapPath)) {
    sb_json_fail(503, 'bootstrap_missing', 'Create api/firebase-admin-bootstrap.local.php (see firebase-admin-bootstrap.example.php).');
}

/** @var array<string, mixed> $cfg */
$cfg = require $bootstrapPath;
$saPath = isset($cfg['service_account_json_path']) ? (string) $cfg['service_account_json_path'] : '';
$dbUrl = isset($cfg['firebase_database_url']) ? rtrim((string) $cfg['firebase_database_url'], '/') : '';

if ($saPath === '' || $dbUrl === '' || !is_readable($saPath)) {
    sb_json_fail(503, 'config_invalid', 'service_account_json_path / firebase_database_url not configured.');
}

$tokenRes = firebase_service_account_access_token($saPath);
if (!empty($tokenRes['error'])) {
    sb_json_fail(503, 'oauth_failed', (string) $tokenRes['error']);
}
$token = (string) $tokenRes['access_token'];

$clientId = sb_normalize_client_id((string) ($_GET['clientId'] ?? ''));
$site = sb_normalize_site_key((string) ($_GET['site'] ?? ''));

if ($clientId === '' && $site !== '') {
    $mapPath = 'publicSiteMappings/' . $site;
    $mapRes = firebase_rtdb_get($dbUrl, $mapPath, $token);
    if (!empty($mapRes['error'])) {
        sb_json_fail(502, 'mapping_fetch_failed', (string) $mapRes['error']);
    }
    $raw = $mapRes['data'] ?? null;
    if (is_string($raw)) {
        $clientId = sb_normalize_client_id($raw);
    }
}

if ($clientId === '') {
    sb_json_fail(400, 'missing_client', 'Provide clientId= or site= (subdomain).');
}

$settingsRes = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings', $token);
if (!empty($settingsRes['error'])) {
    sb_json_fail(502, 'settings_fetch_failed', (string) $settingsRes['error']);
}
$settings = is_array($settingsRes['data'] ?? null) ? $settingsRes['data'] : [];

$productsRes = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/products', $token);
if (!empty($productsRes['error'])) {
    sb_json_fail(502, 'products_fetch_failed', (string) $productsRes['error']);
}

$productsRaw = $productsRes['data'] ?? null;
$productsVal = null;
if (is_array($productsRaw) && $productsRaw !== []) {
    $entries = [];
    foreach ($productsRaw as $pid => $val) {
        if (!is_array($val)) {
            continue;
        }
        $id = (string) $pid;
        $createdAt = isset($val['createdAt']) ? (int) $val['createdAt'] : 0;
        $entries[] = ['id' => $id, 'createdAt' => $createdAt, 'val' => $val];
    }
    usort($entries, static function (array $a, array $b): int {
        return $b['createdAt'] <=> $a['createdAt'];
    });
    $slice = array_slice($entries, 0, HOME_PREVIEW_PRODUCT_CAP);
    $productsVal = [];
    foreach ($slice as $row) {
        $productsVal[$row['id']] = $row['val'];
    }
}

echo json_encode([
    'ok' => true,
    'clientId' => $clientId,
    'settings' => $settings,
    'productsVal' => $productsVal,
    'previewLimit' => HOME_PREVIEW_PRODUCT_CAP,
    'ts' => (int) round(microtime(true) * 1000),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
