-- 为 trades 表增加 created_at（创建时间）字段（仅当不存在时）
-- 用于持仓/订单展示「开仓时间」时至少有创建时间可显示；与 init.sql 中定义一致。

-- MySQL 5.7+：通过 procedure 判断后添加，避免重复执行报错
DELIMITER //
DROP PROCEDURE IF EXISTS add_created_at_to_trades_if_missing//
CREATE PROCEDURE add_created_at_to_trades_if_missing()
BEGIN
  IF (SELECT COUNT(*) FROM information_schema.COLUMNS
      WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'trades' AND COLUMN_NAME = 'created_at') = 0 THEN
    ALTER TABLE trades
      ADD COLUMN created_at INT UNSIGNED NULL COMMENT '创建时间（Unix时间戳秒数）' AFTER status;
    UPDATE trades SET created_at = COALESCE(entry_time, UNIX_TIMESTAMP()) WHERE created_at IS NULL;
    ALTER TABLE trades
      MODIFY COLUMN created_at INT UNSIGNED NOT NULL DEFAULT (UNIX_TIMESTAMP()) COMMENT '创建时间（Unix时间戳秒数）';
  END IF;
END//
DELIMITER ;
CALL add_created_at_to_trades_if_missing();
DROP PROCEDURE IF EXISTS add_created_at_to_trades_if_missing;
