CREATE TABLE IF NOT EXISTS `automation_execution_logs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `event_type` VARCHAR(64) NOT NULL,
    `rule_id` INT UNSIGNED DEFAULT NULL,
    `rule_name` VARCHAR(128) NOT NULL,
    `order_id` INT UNSIGNED NOT NULL,
    `execution_status` VARCHAR(16) NOT NULL,
    `result_message` VARCHAR(500) DEFAULT NULL,
    `context_json` JSON DEFAULT NULL,
    `executed_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    INDEX `auto_exec_logs_executed_idx` (`executed_at`),
    INDEX `auto_exec_logs_event_idx` (`event_type`),
    INDEX `auto_exec_logs_status_idx` (`execution_status`),
    INDEX `auto_exec_logs_rule_idx` (`rule_id`),
    INDEX `auto_exec_logs_order_idx` (`order_id`),
    CONSTRAINT `auto_exec_logs_rule_fk` FOREIGN KEY (`rule_id`) REFERENCES `automation_rules` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
    CONSTRAINT `auto_exec_logs_order_fk` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO cron_schedules (job_type, interval_seconds, priority, max_attempts, payload, enabled, last_run_at, next_run_at, created_at, updated_at)
VALUES ('automation_history_cleanup', 86400, 70, 1, JSON_OBJECT('days', 30), 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);
