-- System kolejki zadań cron
-- Wersja: 0.324

CREATE TABLE IF NOT EXISTS pp_cron_jobs (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    job_type VARCHAR(50) NOT NULL,
    status ENUM('pending','processing','completed','failed','cancelled') NOT NULL DEFAULT 'pending',
    priority TINYINT UNSIGNED NOT NULL DEFAULT 100,
    payload TEXT NULL,
    result TEXT NULL,
    attempts SMALLINT UNSIGNED NOT NULL DEFAULT 0,
    max_attempts SMALLINT UNSIGNED NOT NULL DEFAULT 10,
    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,
    INDEX idx_status_priority_scheduled (status, priority, scheduled_at),
    INDEX idx_job_type (job_type),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS pp_cron_schedules (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    job_type VARCHAR(50) NOT NULL UNIQUE,
    interval_seconds INT UNSIGNED NOT NULL,
    priority TINYINT UNSIGNED NOT NULL DEFAULT 100,
    max_attempts SMALLINT UNSIGNED NOT NULL DEFAULT 3,
    payload TEXT 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,
    INDEX idx_enabled_next_run (enabled, next_run_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Harmonogramy zadań
INSERT INTO pp_cron_schedules (job_type, interval_seconds, priority, max_attempts) VALUES
('apilo_token_keepalive', 240, 10, 3),
('apilo_send_order', 60, 40, 10),
('apilo_product_sync', 600, 100, 3),
('apilo_pricelist_sync', 3600, 100, 3),
('apilo_status_poll', 600, 100, 3),
('price_history', 86400, 100, 3),
('order_analysis', 600, 100, 3),
('trustmate_invitation', 600, 200, 3),
('google_xml_feed', 3600, 200, 3);
