-- M-AI-02-07: 新增 Transactional Outbox 数据模型
-- 用于可靠发布 BullMQ Job 和领域事件（本批不实现 Dispatcher）

CREATE TABLE `OutboxEvent` (
    `id` VARCHAR(191) NOT NULL,
    `eventType` VARCHAR(128) NOT NULL,
    `aggregateType` VARCHAR(64) NOT NULL,
    `aggregateId` VARCHAR(255) NOT NULL,
    `dedupeKey` VARCHAR(255) NOT NULL,
    `payload` JSON NOT NULL,
    `status` VARCHAR(32) NOT NULL DEFAULT 'pending',
    `attemptCount` INT NOT NULL DEFAULT 0,
    `availableAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `lockedAt` DATETIME(3) NULL,
    `lockedBy` VARCHAR(100) NULL,
    `publishedAt` DATETIME(3) NULL,
    `lastErrorCode` VARCHAR(100) NULL,
    `lastErrorMessage` TEXT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    UNIQUE INDEX `OutboxEvent_dedupeKey_key` (`dedupeKey`),
    INDEX `OutboxEvent_status_availableAt_idx` (`status`, `availableAt`),
    INDEX `OutboxEvent_lockedAt_idx` (`lockedAt`),
    INDEX `OutboxEvent_aggregateType_aggregateId_idx` (`aggregateType`, `aggregateId`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
