-- 设置字符集和排序规则
SET NAMES utf8mb4;
SET GLOBAL time_zone = '+8:00';

-- 创建数据库（如果不存在）
CREATE DATABASE IF NOT EXISTS ai_dressing CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 确保使用正确的数据库
USE ai_dressing;

-- 创建用户（如果不存在）
-- 注意：在Docker环境中，这些通常由MYSQL_USER和MYSQL_PASSWORD环境变量处理
-- 此处作为备用，确保权限正确设置
CREATE USER IF NOT EXISTS 'ai_user'@'%' IDENTIFIED BY 'yourpassword';
GRANT ALL PRIVILEGES ON ai_dressing.* TO 'ai_user'@'%';
FLUSH PRIVILEGES;

-- 设置必要的MySQL配置
SET GLOBAL max_connections = 500;
SET GLOBAL connect_timeout = 60;
SET GLOBAL wait_timeout = 600;
SET GLOBAL interactive_timeout = 600;
SET GLOBAL max_allowed_packet = 16777216; -- 16MB

-- 创建一个测试表，验证初始化是否成功
CREATE TABLE IF NOT EXISTS `system_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key` varchar(50) NOT NULL,
  `value` text NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `key` (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 插入初始数据
INSERT INTO `system_info` (`key`, `value`, `description`) 
VALUES 
('system_name', 'AI Dressing System', '系统名称'),
('version', '1.0.0', '系统版本'),
('init_date', CURRENT_TIMESTAMP, '系统初始化日期')
ON DUPLICATE KEY UPDATE 
`value` = VALUES(`value`), 
`description` = VALUES(`description`),
`updated_at` = CURRENT_TIMESTAMP; 