<?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();
$snapshot = $input['snapshot'] ?? [];
$deviceId = trim((string)($input['device_id'] ?? ''));
$transactionUuid = trim((string)($input['transaction_uuid'] ?? ''));

if (!is_array($snapshot)) {
    sync_api_json_error(400, 'INVALID_REQUEST', 'snapshot must be an object.');
}

try {
    $tenant = golder_tenant_pdo_from_customer($customer);
    $result = sync_api_apply_profile_snapshot($tenant, $snapshot, $deviceId, $transactionUuid);

    golder_json_response([
        'status' => 'ok',
        'result' => $result,
        'max_event_id' => (int)($result['max_event_id'] ?? 0),
        'event_count' => (int)($result['event_count'] ?? 0),
        'duplicate' => !empty($result['duplicate']),
    ]);
} catch (Throwable $e) {
    sync_api_fail_from_exception($e, 'PROFILE_IMPORT_FAILED');
}


