CREATE TABLE IF NOT EXISTS rvx_sync_batches (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    lead_count INT UNSIGNED NOT NULL DEFAULT 0,
    payload LONGTEXT NOT NULL,
    last_result LONGTEXT NULL,
    attempts INT UNSIGNED NOT NULL DEFAULT 0,
    max_attempts INT UNSIGNED NOT NULL DEFAULT 5,
    locked_at DATETIME NULL,
    locked_by VARCHAR(100) NULL,
    available_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    started_at DATETIME NULL,
    finished_at DATETIME NULL,
    last_error VARCHAR(1000) NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE INDEX idx_rvx_sync_batches_status_available ON rvx_sync_batches (status, available_at);
CREATE INDEX idx_rvx_sync_batches_locked ON rvx_sync_batches (locked_at);

ALTER TABLE leads
    ADD INDEX idx_leads_rvx_sync_status (needs_rvx_sync, rvx_sync_status, rvx_sync_locked_at);
