CREATE TABLE IF NOT EXISTS integration_order_sync_state (
    integration_id INT UNSIGNED NOT NULL PRIMARY KEY,
    last_synced_order_updated_at DATETIME NULL,
    last_synced_source_order_id VARCHAR(64) NULL,
    last_synced_external_order_id VARCHAR(128) NULL,
    last_run_at DATETIME NULL,
    last_success_at DATETIME NULL,
    last_error VARCHAR(500) NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE integration_order_sync_state
    ADD COLUMN IF NOT EXISTS last_synced_order_updated_at DATETIME NULL AFTER integration_id,
    ADD COLUMN IF NOT EXISTS last_synced_source_order_id VARCHAR(64) NULL AFTER last_synced_order_updated_at,
    ADD COLUMN IF NOT EXISTS last_success_at DATETIME NULL AFTER last_run_at,
    ADD COLUMN IF NOT EXISTS created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER last_error;

INSERT INTO cron_schedules (
    job_type, interval_seconds, priority, max_attempts, payload, enabled, last_run_at, next_run_at, created_at, updated_at
) VALUES (
    'allegro_orders_import',
    300,
    20,
    3,
    JSON_OBJECT('max_pages', 5, 'page_limit', 50, 'max_orders', 200),
    1,
    NULL,
    NOW(),
    NOW(),
    NOW()
)
ON DUPLICATE KEY UPDATE
    interval_seconds = VALUES(interval_seconds),
    priority = VALUES(priority),
    max_attempts = VALUES(max_attempts),
    payload = VALUES(payload),
    enabled = VALUES(enabled),
    updated_at = VALUES(updated_at);
