-- M-AI-02-03: Expand AiAnalysisJob 身份、路由与幂等字段
-- ADR-002 §2.1 身份与路由字段集

-- 1. jobType 扩展 VARCHAR(32) → VARCHAR(64)
ALTER TABLE `AiAnalysisJob`
  MODIFY COLUMN `jobType` VARCHAR(64) NOT NULL;

-- 2. 新增身份与路由字段
ALTER TABLE `AiAnalysisJob`
  ADD COLUMN `triggerType` VARCHAR(32) NOT NULL DEFAULT 'api' AFTER `jobType`,
  ADD COLUMN `queueName` VARCHAR(64) NOT NULL DEFAULT 'ai-interactive' AFTER `triggerType`,
  ADD COLUMN `priority` INT NOT NULL DEFAULT 0 AFTER `queueName`,
  ADD COLUMN `targetType` VARCHAR(32) NULL AFTER `priority`,
  ADD COLUMN `targetId` VARCHAR(255) NULL AFTER `targetType`,
  ADD COLUMN `parentJobId` VARCHAR(255) NULL AFTER `targetId`,
  ADD COLUMN `idempotencyKey` VARCHAR(255) NULL AFTER `parentJobId`,
  ADD COLUMN `retriedFromJobId` VARCHAR(255) NULL AFTER `idempotencyKey`,
  ADD COLUMN `inputRef` VARCHAR(255) NULL AFTER `retriedFromJobId`,
  ADD COLUMN `inputSchemaVersion` VARCHAR(100) NULL AFTER `inputRef`;

-- 3. Unique 约束（idempotencyKey — MySQL UNIQUE 允许多个 NULL）
ALTER TABLE `AiAnalysisJob`
  ADD UNIQUE INDEX `AiAnalysisJob_idempotencyKey_key` (`idempotencyKey`);

-- 4. 复合索引
ALTER TABLE `AiAnalysisJob`
  ADD INDEX `AiAnalysisJob_userId_jobType_createdAt_idx` (`userId`, `jobType`, `createdAt`),
  ADD INDEX `AiAnalysisJob_targetType_targetId_idx` (`targetType`, `targetId`),
  ADD INDEX `AiAnalysisJob_parentJobId_idx` (`parentJobId`);

-- 5. 自引用 FK（parentJobId → id）
ALTER TABLE `AiAnalysisJob`
  ADD CONSTRAINT `AiAnalysisJob_parentJobId_fkey`
    FOREIGN KEY (`parentJobId`) REFERENCES `AiAnalysisJob`(`id`)
    ON DELETE SET NULL ON UPDATE CASCADE;
