<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_bootstrap.php';
require_once dirname(__DIR__, 3) . '/common/auth_middleware.php';

if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    sync_api_json_response(['status' => 'error', 'code' => 'METHOD_NOT_ALLOWED'], 405);
}

$master = golder_master_pdo();
$tokenRow = golder_auth_token($master, 'desktop_sync');
$customerId = (int)($tokenRow['customer_id'] ?? 0);
if ($customerId <= 0) {
    sync_api_json_response(['status' => 'error', 'code' => 'UNAUTHORIZED'], 401);
}
sync_api_require_profile_sync_customer($customerId);

golder_apply_default_rate_limit($master, 'sync_pull_' . $customerId, 120, 60);

$body = sync_api_read_json_body();
$profileId = trim((string)($body['profile_id'] ?? ''));
$deviceId = trim((string)($body['device_id'] ?? ''));
$lastPulled = (int)($body['last_pulled_event_id'] ?? 0);
$dbName = trim((string)($body['db_name'] ?? ''));

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

try {
    $tenantInfo = sync_api_profile_tenant_pdo($profileId, $dbName, $customerId, false);
    if (!$tenantInfo || !($tenantInfo['pdo'] instanceof PDO)) {
        sync_api_json_response(
            ['status' => 'error', 'code' => 'PROFILE_DB_NOT_FOUND', 'message' => 'Profile database not found'],
            404
        );
    }
    /** @var PDO $db */
    $db = $tenantInfo['pdo'];
    sync_api_ensure_global_events_table($db);
    $profileMissing = !sync_api_profile_exists($db, $profileId);

    $sql = "
        SELECT id, transaction_uuid, device_id, profile_id, table_name, action_type, record_id, payload_json, created_at
        FROM global_sync_events
        WHERE (profile_id = ? OR table_name = 'profiles' OR profile_id IS NULL OR profile_id = '')
          AND id > ?
          AND (
            action_type = 'ROLLBACK'
            OR ? = ''
            OR device_id IS NULL
            OR device_id = ''
            OR device_id <> ?
          )
        ORDER BY id ASC
        LIMIT 500
    ";
    $st = $db->prepare($sql);
    $st->execute([$profileId, $lastPulled, $deviceId, $deviceId]);
    $rows = $st->fetchAll() ?: [];

    $events = [];
    $maxId = $lastPulled;
    foreach ($rows as $row) {
        $eventId = (int)($row['id'] ?? 0);
        if ($eventId > $maxId) {
            $maxId = $eventId;
        }
        $payload = $row['payload_json'] ?? null;
        if (is_string($payload)) {
            $decoded = json_decode($payload, true);
            $payload = is_array($decoded) ? $decoded : [];
        } elseif (!is_array($payload)) {
            $payload = [];
        }
        $events[] = [
            'id' => $eventId,
            'transaction_uuid' => (string)($row['transaction_uuid'] ?? ''),
            'device_id' => (string)($row['device_id'] ?? ''),
            'profile_id' => (string)($row['profile_id'] ?? ''),
            'table_name' => (string)($row['table_name'] ?? ''),
            'action_type' => (string)($row['action_type'] ?? ''),
            'record_id' => (string)($row['record_id'] ?? ''),
            'payload_json' => $payload,
            'created_at' => (string)($row['created_at'] ?? ''),
        ];
    }

    sync_api_json_response([
        'status' => 'ok',
        'events' => $events,
        'last_event_id' => $maxId,
        'profile_missing' => $profileMissing,
    ], 200);
} catch (Throwable $e) {
    sync_api_log('SYNC_PULL_ERROR', [
        'profile_id' => $profileId,
        'device_id' => $deviceId,
        'last_in' => $lastPulled,
        'customer_id' => $customerId,
        'error' => $e->getMessage(),
    ]);
    sync_api_json_response(['status' => 'error', 'code' => 'SERVER_ERROR', 'message' => $e->getMessage()], 500);
}


