-- M-AI-02-04: Expand AiAnalysisJob 生命周期、执行与输出字段
-- ADR-002 §2.1 生命周期/执行/凭据/输出字段集

-- 1. 生命周期与执行字段
ALTER TABLE `AiAnalysisJob`
  ADD COLUMN `lifecycleStatus` VARCHAR(32) NULL AFTER `status`,
  ADD COLUMN `lockedBy` VARCHAR(100) NULL AFTER `lifecycleStatus`,
  ADD COLUMN `lockedAt` DATETIME(3) NULL AFTER `lockedBy`,
  ADD COLUMN `lockUntil` DATETIME(3) NULL AFTER `lockedAt`,
  ADD COLUMN `cancelRequestedAt` DATETIME(3) NULL AFTER `lockUntil`,
  ADD COLUMN `attemptCount` INT NOT NULL DEFAULT 0 AFTER `cancelRequestedAt`,
  ADD COLUMN `maxAttempts` INT NOT NULL DEFAULT 3 AFTER `attemptCount`,
  ADD COLUMN `timeoutMs` INT NOT NULL DEFAULT 120000 AFTER `maxAttempts`;

-- 2. 凭据与模型字段
ALTER TABLE `AiAnalysisJob`
  ADD COLUMN `credentialMode` VARCHAR(32) NOT NULL DEFAULT 'platform_key' AFTER `timeoutMs`,
  ADD COLUMN `credentialId` VARCHAR(255) NULL AFTER `credentialMode`,
  ADD COLUMN `modelTier` VARCHAR(32) NOT NULL DEFAULT 'primary' AFTER `credentialId`,
  ADD COLUMN `modelProvider` VARCHAR(32) NOT NULL DEFAULT 'deepseek' AFTER `modelTier`,
  ADD COLUMN `modelName` VARCHAR(64) NOT NULL DEFAULT 'deepseek-chat' AFTER `modelProvider`;

-- 3. 输入输出字段
ALTER TABLE `AiAnalysisJob`
  ADD COLUMN `promptKey` VARCHAR(128) NULL AFTER `modelName`,
  ADD COLUMN `promptVersion` VARCHAR(100) NULL AFTER `promptKey`,
  ADD COLUMN `outputSchemaVersion` VARCHAR(100) NULL AFTER `promptVersion`,
  ADD COLUMN `outputHash` VARCHAR(255) NULL AFTER `outputSchemaVersion`,
  ADD COLUMN `validatedOutput` JSON NULL AFTER `outputHash`;

-- 4. 错误字段 + 列重命名
ALTER TABLE `AiAnalysisJob`
  ADD COLUMN `errorCode` VARCHAR(100) NULL AFTER `validatedOutput`,
  ADD COLUMN `publicErrorMessage` VARCHAR(500) NULL AFTER `errorCode`;

-- 4a. 列重命名 1/2: errorMessage → internalErrorMessage
-- 理由：区分公开错误(publicErrorMessage)与内部错误(internalErrorMessage)
ALTER TABLE `AiAnalysisJob`
  CHANGE COLUMN `errorMessage` `internalErrorMessage` TEXT NULL;

-- 4b. 列重命名 2/2: completedAt → finishedAt
-- 理由：与 lifecycleStatus 'succeeded' 去歧义，与 startedAt 配对
ALTER TABLE `AiAnalysisJob`
  CHANGE COLUMN `completedAt` `finishedAt` DATETIME(3) NULL;

-- 5. 索引：Worker 轮询
ALTER TABLE `AiAnalysisJob`
  ADD INDEX `AiAnalysisJob_lifecycleStatus_createdAt_idx` (`lifecycleStatus`, `createdAt`),
  ADD INDEX `AiAnalysisJob_queueName_lifecycleStatus_createdAt_idx` (`queueName`, `lifecycleStatus`, `createdAt`);
