-- Baseline migration for the current DevOps platform schema.
-- Existing production tables are marked as applied by the Jenkins deploy script
-- before running `prisma migrate deploy`; fresh databases execute this file.

-- CreateTable
CREATE TABLE `projects` (
    `id` VARCHAR(191) NOT NULL,
    `key` VARCHAR(191) NOT NULL,
    `name` VARCHAR(191) NOT NULL,
    `repositoryUrl` VARCHAR(512) NULL,
    `defaultBranch` VARCHAR(191) NOT NULL DEFAULT 'develop',
    `status` ENUM('ACTIVE', 'ARCHIVED') NOT NULL DEFAULT 'ACTIVE',
    `metadata` JSON NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    UNIQUE INDEX `projects_key_key`(`key`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `environments` (
    `id` VARCHAR(191) NOT NULL,
    `projectId` VARCHAR(191) NOT NULL,
    `name` ENUM('TEST', 'PRODUCTION') NOT NULL,
    `displayName` VARCHAR(191) NOT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    INDEX `environments_projectId_idx`(`projectId`),
    UNIQUE INDEX `environments_projectId_name_key`(`projectId`, `name`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `deploy_jobs` (
    `id` VARCHAR(191) NOT NULL,
    `projectId` VARCHAR(191) NOT NULL,
    `environmentId` VARCHAR(191) NOT NULL,
    `jenkinsJobPath` VARCHAR(191) NOT NULL,
    `jenkinsParameters` JSON NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    INDEX `deploy_jobs_environmentId_idx`(`environmentId`),
    UNIQUE INDEX `deploy_jobs_projectId_environmentId_key`(`projectId`, `environmentId`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `deploy_runs` (
    `id` VARCHAR(191) NOT NULL,
    `projectId` VARCHAR(191) NOT NULL,
    `environmentId` VARCHAR(191) NOT NULL,
    `jobId` VARCHAR(191) NULL,
    `status` ENUM('PENDING', 'QUEUED', 'RUNNING', 'SUCCESS', 'FAILED', 'CANCELED') NOT NULL DEFAULT 'PENDING',
    `trigger` ENUM('MANUAL', 'GITEA_WEBHOOK', 'RETRY') NOT NULL DEFAULT 'MANUAL',
    `ref` VARCHAR(191) NOT NULL,
    `operator` VARCHAR(191) NOT NULL,
    `idempotencyKey` VARCHAR(191) NOT NULL,
    `jenkinsQueueId` VARCHAR(191) NULL,
    `jenkinsBuildNumber` INTEGER NULL,
    `failureSummary` TEXT NULL,
    `metadata` JSON NULL,
    `version` INTEGER NOT NULL DEFAULT 1,
    `startedAt` DATETIME(3) NULL,
    `finishedAt` DATETIME(3) NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    UNIQUE INDEX `deploy_runs_idempotencyKey_key`(`idempotencyKey`),
    INDEX `deploy_runs_projectId_environmentId_createdAt_idx`(`projectId`, `environmentId`, `createdAt`),
    INDEX `deploy_runs_status_createdAt_idx`(`status`, `createdAt`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `run_steps` (
    `id` VARCHAR(191) NOT NULL,
    `deployRunId` VARCHAR(191) NOT NULL,
    `bpmnNodeId` VARCHAR(191) NOT NULL,
    `name` VARCHAR(191) NOT NULL,
    `status` ENUM('PENDING', 'RUNNING', 'SUCCESS', 'FAILED', 'SKIPPED', 'CANCELED') NOT NULL DEFAULT 'PENDING',
    `order` INTEGER NOT NULL DEFAULT 0,
    `errorSummary` TEXT NULL,
    `metadata` JSON NULL,
    `startedAt` DATETIME(3) NULL,
    `finishedAt` DATETIME(3) NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    INDEX `run_steps_deployRunId_order_idx`(`deployRunId`, `order`),
    UNIQUE INDEX `run_steps_deployRunId_bpmnNodeId_key`(`deployRunId`, `bpmnNodeId`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `audit_logs` (
    `id` VARCHAR(191) NOT NULL,
    `deployRunId` VARCHAR(191) NULL,
    `actorId` VARCHAR(191) NULL,
    `actorName` VARCHAR(191) NULL,
    `action` VARCHAR(191) NOT NULL,
    `resourceType` VARCHAR(191) NOT NULL,
    `resourceId` VARCHAR(191) NULL,
    `requestId` VARCHAR(191) NULL,
    `sourceIp` VARCHAR(191) NULL,
    `userAgent` VARCHAR(191) NULL,
    `before` JSON NULL,
    `after` JSON NULL,
    `parameterDigest` JSON NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    INDEX `audit_logs_resourceType_resourceId_createdAt_idx`(`resourceType`, `resourceId`, `createdAt`),
    INDEX `audit_logs_actorId_createdAt_idx`(`actorId`, `createdAt`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `users` (
    `id` VARCHAR(191) NOT NULL,
    `account` VARCHAR(191) NOT NULL,
    `displayName` VARCHAR(191) NOT NULL,
    `role` ENUM('SUPER_ADMIN', 'MEMBER') NOT NULL DEFAULT 'MEMBER',
    `status` ENUM('ACTIVE', 'DISABLED') NOT NULL DEFAULT 'ACTIVE',
    `passwordHash` TEXT NOT NULL,
    `mustChangePassword` BOOLEAN NOT NULL DEFAULT false,
    `passwordVersion` INTEGER NOT NULL DEFAULT 1,
    `lastLoginAt` DATETIME(3) NULL,
    `createdById` VARCHAR(191) NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    UNIQUE INDEX `users_account_key`(`account`),
    INDEX `users_role_status_idx`(`role`, `status`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `project_member_permissions` (
    `id` VARCHAR(191) NOT NULL,
    `userId` VARCHAR(191) NOT NULL,
    `projectId` VARCHAR(191) NOT NULL,
    `level` ENUM('READ', 'BUILD') NOT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    INDEX `project_member_permissions_projectId_idx`(`projectId`),
    UNIQUE INDEX `project_member_permissions_userId_projectId_key`(`userId`, `projectId`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `platform_messages` (
    `id` VARCHAR(191) NOT NULL,
    `type` ENUM('PASSWORD_RESET_REQUEST') NOT NULL,
    `status` ENUM('PENDING', 'HANDLED') NOT NULL DEFAULT 'PENDING',
    `title` VARCHAR(191) NOT NULL,
    `content` TEXT NOT NULL,
    `requesterId` VARCHAR(191) NULL,
    `requesterAccount` VARCHAR(191) NOT NULL,
    `targetResourceType` VARCHAR(191) NULL,
    `targetResourceId` VARCHAR(191) NULL,
    `metadata` JSON NULL,
    `handledById` VARCHAR(191) NULL,
    `handledAt` DATETIME(3) NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    INDEX `platform_messages_type_status_createdAt_idx`(`type`, `status`, `createdAt`),
    INDEX `platform_messages_requesterId_status_idx`(`requesterId`, `status`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `secrets` (
    `id` VARCHAR(191) NOT NULL,
    `provider` ENUM('JENKINS', 'GITEA', 'WECOM', 'LLM', 'INTERNAL') NOT NULL,
    `scopeType` VARCHAR(191) NOT NULL,
    `scopeId` VARCHAR(191) NOT NULL,
    `name` VARCHAR(191) NOT NULL,
    `encryptedValue` TEXT NOT NULL,
    `version` INTEGER NOT NULL DEFAULT 1,
    `rotatedAt` DATETIME(3) NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    INDEX `secrets_scopeType_scopeId_idx`(`scopeType`, `scopeId`),
    UNIQUE INDEX `secrets_provider_scopeType_scopeId_name_key`(`provider`, `scopeType`, `scopeId`, `name`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `agent_invocations` (
    `id` VARCHAR(191) NOT NULL,
    `deployRunId` VARCHAR(191) NULL,
    `purpose` ENUM('RISK_SUMMARY', 'FAILURE_DIAGNOSIS', 'RUNBOOK_QA', 'RELEASE_NOTES', 'INCIDENT_REVIEW') NOT NULL,
    `actorId` VARCHAR(191) NULL,
    `actorName` VARCHAR(191) NULL,
    `model` VARCHAR(191) NULL,
    `promptVersion` VARCHAR(191) NOT NULL,
    `inputDigest` JSON NOT NULL,
    `outputDigest` JSON NULL,
    `tokenEstimate` INTEGER NULL,
    `status` VARCHAR(191) NOT NULL,
    `errorSummary` TEXT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `completedAt` DATETIME(3) NULL,

    INDEX `agent_invocations_purpose_createdAt_idx`(`purpose`, `createdAt`),
    INDEX `agent_invocations_deployRunId_createdAt_idx`(`deployRunId`, `createdAt`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `outbox_messages` (
    `id` VARCHAR(191) NOT NULL,
    `deployRunId` VARCHAR(191) NULL,
    `channel` VARCHAR(191) NOT NULL,
    `template` VARCHAR(191) NOT NULL,
    `payload` JSON NOT NULL,
    `status` ENUM('PENDING', 'SENT', 'FAILED', 'DEAD') NOT NULL DEFAULT 'PENDING',
    `attemptCount` INTEGER NOT NULL DEFAULT 0,
    `nextAttemptAt` DATETIME(3) NULL,
    `lastError` TEXT NULL,
    `idempotencyKey` VARCHAR(191) NOT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    UNIQUE INDEX `outbox_messages_idempotencyKey_key`(`idempotencyKey`),
    INDEX `outbox_messages_status_nextAttemptAt_idx`(`status`, `nextAttemptAt`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `environments` ADD CONSTRAINT `environments_projectId_fkey` FOREIGN KEY (`projectId`) REFERENCES `projects`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `deploy_jobs` ADD CONSTRAINT `deploy_jobs_projectId_fkey` FOREIGN KEY (`projectId`) REFERENCES `projects`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `deploy_jobs` ADD CONSTRAINT `deploy_jobs_environmentId_fkey` FOREIGN KEY (`environmentId`) REFERENCES `environments`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `deploy_runs` ADD CONSTRAINT `deploy_runs_projectId_fkey` FOREIGN KEY (`projectId`) REFERENCES `projects`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `deploy_runs` ADD CONSTRAINT `deploy_runs_environmentId_fkey` FOREIGN KEY (`environmentId`) REFERENCES `environments`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `deploy_runs` ADD CONSTRAINT `deploy_runs_jobId_fkey` FOREIGN KEY (`jobId`) REFERENCES `deploy_jobs`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `run_steps` ADD CONSTRAINT `run_steps_deployRunId_fkey` FOREIGN KEY (`deployRunId`) REFERENCES `deploy_runs`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `audit_logs` ADD CONSTRAINT `audit_logs_deployRunId_fkey` FOREIGN KEY (`deployRunId`) REFERENCES `deploy_runs`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `project_member_permissions` ADD CONSTRAINT `project_member_permissions_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `project_member_permissions` ADD CONSTRAINT `project_member_permissions_projectId_fkey` FOREIGN KEY (`projectId`) REFERENCES `projects`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `platform_messages` ADD CONSTRAINT `platform_messages_requesterId_fkey` FOREIGN KEY (`requesterId`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `platform_messages` ADD CONSTRAINT `platform_messages_handledById_fkey` FOREIGN KEY (`handledById`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `agent_invocations` ADD CONSTRAINT `agent_invocations_deployRunId_fkey` FOREIGN KEY (`deployRunId`) REFERENCES `deploy_runs`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `outbox_messages` ADD CONSTRAINT `outbox_messages_deployRunId_fkey` FOREIGN KEY (`deployRunId`) REFERENCES `deploy_runs`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
