-- Add user profile and avatar fields to an existing financial_system database.
-- Execute with:
--   mysql -h localhost -P 3306 -u root -p12345678 < financial_system/database/sql/upgrade_20260616_user_profile.sql

USE `financial_system`;

SET @has_avatar_url := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'avatar_url'
);
SET @ddl := IF(@has_avatar_url = 0,
  'ALTER TABLE `users` ADD COLUMN `avatar_url` VARCHAR(512) NOT NULL DEFAULT '''' COMMENT ''用户头像URL或静态资源路径''',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_email := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'email'
);
SET @ddl := IF(@has_email = 0,
  'ALTER TABLE `users` ADD COLUMN `email` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''用户邮箱''',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_phone := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'phone'
);
SET @ddl := IF(@has_phone = 0,
  'ALTER TABLE `users` ADD COLUMN `phone` VARCHAR(32) NOT NULL DEFAULT '''' COMMENT ''用户手机号''',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_department := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'department'
);
SET @ddl := IF(@has_department = 0,
  'ALTER TABLE `users` ADD COLUMN `department` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''用户所属部门''',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_position_title := (
  SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'position_title'
);
SET @ddl := IF(@has_position_title = 0,
  'ALTER TABLE `users` ADD COLUMN `position_title` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''用户职位或岗位名称''',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE `users`
SET
  `department` = IF(`department` = '', '系统管理', `department`),
  `position_title` = IF(`position_title` = '', '超级管理员', `position_title`)
WHERE `username` = 'admin';
