CREATE TABLE IF NOT EXISTS cron_jobs (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    job_type VARCHAR(80) NOT NULL,
    status ENUM('pending', 'processing', 'completed', 'failed', 'cancelled') NOT NULL DEFAULT 'pending',
    priority TINYINT UNSIGNED NOT NULL DEFAULT 100,
    payload JSON NULL,
    result JSON NULL,
    attempts SMALLINT UNSIGNED NOT NULL DEFAULT 0,
    max_attempts SMALLINT UNSIGNED NOT NULL DEFAULT 3,
    last_error VARCHAR(500) NULL,
    scheduled_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    started_at DATETIME NULL,
    completed_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY cron_jobs_status_priority_scheduled_idx (status, priority, scheduled_at),
    KEY cron_jobs_job_type_idx (job_type),
    KEY cron_jobs_scheduled_at_idx (scheduled_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cron_schedules (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    job_type VARCHAR(80) NOT NULL,
    interval_seconds INT UNSIGNED NOT NULL,
    priority TINYINT UNSIGNED NOT NULL DEFAULT 100,
    max_attempts SMALLINT UNSIGNED NOT NULL DEFAULT 3,
    payload JSON NULL,
    enabled TINYINT(1) NOT NULL DEFAULT 1,
    last_run_at DATETIME NULL,
    next_run_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY cron_schedules_job_type_unique (job_type),
    KEY cron_schedules_enabled_next_run_idx (enabled, next_run_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS app_settings (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(120) NOT NULL,
    setting_value TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY app_settings_setting_key_unique (setting_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO app_settings (setting_key, setting_value, created_at, updated_at)
VALUES
    ('cron_run_on_web', '0', NOW(), NOW()),
    ('cron_web_limit', '5', NOW(), NOW())
ON DUPLICATE KEY UPDATE
    setting_value = VALUES(setting_value),
    updated_at = VALUES(updated_at);

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_token_refresh',
    3600,
    10,
    3,
    NULL,
    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);
