<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_bootstrap.php';

golder_require_method('POST');
$ctx = golder_api_auth('desktop_sync');
$customer = sync_api_require_profile_sync_customer((int)($ctx['customer_id'] ?? 0));
$input = golder_api_input();
$profileId = trim((string)($input['profile_id'] ?? ''));

if ($profileId === '') {
    sync_api_json_error(400, 'INVALID_REQUEST', 'profile_id is required.');
}

try {
    $tenant = golder_tenant_pdo_from_customer($customer);
    sync_api_ensure_global_events_table($tenant);

    $snapshot = sync_api_build_profile_snapshot($tenant, $profileId);
    $maxEventId = 0;
    try {
        $maxEventId = (int)($tenant->query('SELECT COALESCE(MAX(id), 0) AS max_id FROM global_sync_events')->fetch()['max_id'] ?? 0);
    } catch (Throwable $_ignored) {
        $maxEventId = 0;
    }

    golder_json_response([
        'status' => 'ok',
        'profile_id' => $profileId,
        'snapshot' => $snapshot,
        'max_event_id' => $maxEventId,
    ]);
} catch (Throwable $e) {
    sync_api_fail_from_exception($e, 'PROFILE_EXPORT_FAILED');
}


