-- M-AI-02-08: 扩展 AiUsageLog 的 Job、尝试次数与凭据归属

-- 1. 新增 Job 关联与凭据归属字段
ALTER TABLE `AiUsageLog`
  ADD COLUMN `jobId` VARCHAR(191) NULL AFTER `errorMessage`,
  ADD COLUMN `attemptNo` INT NOT NULL DEFAULT 0 AFTER `jobId`,
  ADD COLUMN `credentialMode` VARCHAR(32) NOT NULL DEFAULT 'platform_key' AFTER `attemptNo`,
  ADD COLUMN `errorCode` VARCHAR(100) NULL AFTER `credentialMode`,
  ADD COLUMN `providerRequestId` VARCHAR(255) NULL AFTER `errorCode`;

-- 2. FK: Job 删除时 SetNull UsageLog（保留审计记录）
ALTER TABLE `AiUsageLog`
  ADD CONSTRAINT `AiUsageLog_jobId_fkey`
    FOREIGN KEY (`jobId`) REFERENCES `AiAnalysisJob`(`id`)
    ON DELETE SET NULL ON UPDATE CASCADE;

-- 3. 索引
ALTER TABLE `AiUsageLog`
  ADD INDEX `AiUsageLog_jobId_attemptNo_idx` (`jobId`, `attemptNo`),
  ADD INDEX `AiUsageLog_provider_model_createdAt_idx` (`provider`, `model`, `createdAt`),
  ADD INDEX `AiUsageLog_errorCode_createdAt_idx` (`errorCode`, `createdAt`);
