-- 创建数据库
CREATE DATABASE IF NOT EXISTS `chat_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建用户并授权
CREATE USER IF NOT EXISTS 'chat_user'@'%' IDENTIFIED BY 'chat_password';
GRANT ALL PRIVILEGES ON `chat_db`.* TO 'chat_user'@'%';
FLUSH PRIVILEGES;

-- 使用数据库
USE `chat_db`;

-- 创建房间表
CREATE TABLE IF NOT EXISTS `rooms` (
  `roomId` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `roomName` VARCHAR(255) NOT NULL,
  `creater` VARCHAR(255) NOT NULL,
  `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 创建消息表
CREATE TABLE IF NOT EXISTS `messages` (
  `messageId` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `roomId` INT UNSIGNED NOT NULL,
  `sender` VARCHAR(255) NOT NULL,
  `content` TEXT NOT NULL,
  `time` BIGINT NOT NULL,
  FOREIGN KEY (`roomId`) REFERENCES `rooms`(`roomId`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 创建用户表
CREATE TABLE IF NOT EXISTS `users` (
  `userId` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `username` VARCHAR(255) UNIQUE NOT NULL,
  `passwordHash` VARCHAR(255) NOT NULL,
  `createdAt` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 创建索引优化查询性能
CREATE INDEX `idx_roomId` ON `messages` (`roomId`);
CREATE INDEX `idx_time` ON `messages` (`time`);
CREATE INDEX `idx_users_username` ON `users` (`username`);