-- CreateTable
CREATE TABLE `KnowledgeGenerationTask` (
  `id` VARCHAR(191) NOT NULL,
  `userId` VARCHAR(191) NOT NULL,
  `knowledgeBaseId` VARCHAR(191) NOT NULL,
  `sourceId` VARCHAR(191) NOT NULL,
  `aiJobId` VARCHAR(191) NULL,
  `requestKind` VARCHAR(32) NOT NULL DEFAULT 'manual_source',
  `status` VARCHAR(32) NOT NULL DEFAULT 'queued',
  `idempotencyKey` VARCHAR(255) NULL,
  `knowledgeItemCount` INTEGER NOT NULL DEFAULT 0,
  `errorCode` VARCHAR(100) NULL,
  `errorMessage` TEXT NULL,
  `requestedAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `startedAt` DATETIME(3) NULL,
  `completedAt` DATETIME(3) NULL,
  `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updatedAt` DATETIME(3) NOT NULL,

  UNIQUE INDEX `KnowledgeGenerationTask_aiJobId_key`(`aiJobId`),
  UNIQUE INDEX `KnowledgeGenerationTask_userId_sourceId_idempotencyKey_key`(`userId`, `sourceId`, `idempotencyKey`),
  INDEX `KnowledgeGenerationTask_userId_status_idx`(`userId`, `status`),
  INDEX `KnowledgeGenerationTask_knowledgeBaseId_status_idx`(`knowledgeBaseId`, `status`),
  INDEX `KnowledgeGenerationTask_sourceId_status_idx`(`sourceId`, `status`),
  INDEX `KnowledgeGenerationTask_sourceId_requestedAt_idx`(`sourceId`, `requestedAt`),
  PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `KnowledgeGenerationTask`
  ADD CONSTRAINT `KnowledgeGenerationTask_userId_fkey`
  FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `KnowledgeGenerationTask`
  ADD CONSTRAINT `KnowledgeGenerationTask_knowledgeBaseId_fkey`
  FOREIGN KEY (`knowledgeBaseId`) REFERENCES `KnowledgeBase`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `KnowledgeGenerationTask`
  ADD CONSTRAINT `KnowledgeGenerationTask_sourceId_fkey`
  FOREIGN KEY (`sourceId`) REFERENCES `KnowledgeSource`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `KnowledgeGenerationTask`
  ADD CONSTRAINT `KnowledgeGenerationTask_aiJobId_fkey`
  FOREIGN KEY (`aiJobId`) REFERENCES `AiAnalysisJob`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
