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;

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,

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

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;

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

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

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

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