-- Add operation log table to an existing financial_system database.
-- Execute with:
--   mysql -h localhost -P 3306 -u root -p12345678 < financial_system/database/sql/upgrade_20260616_operation_logs.sql

USE `financial_system`;

CREATE TABLE IF NOT EXISTS `operation_logs` (
  `id` INT NOT NULL AUTO_INCREMENT COMMENT '日志主键ID',
  `user_id` INT NULL COMMENT '操作用户ID，匿名或用户删除后为空',
  `username` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作用户名快照',
  `role` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '操作用户角色快照',
  `module` VARCHAR(64) NOT NULL COMMENT '业务模块，例如auth、payroll、system',
  `action` VARCHAR(128) NOT NULL COMMENT '操作动作编码，例如login、payroll.excel.calculate',
  `target_type` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作对象类型，例如user、payroll_job、file',
  `target_id` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象ID或业务标识',
  `status` VARCHAR(32) NOT NULL COMMENT '操作状态：success或failed',
  `detail` TEXT NOT NULL COMMENT '操作详情或失败原因',
  `ip_address` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '客户端IP地址',
  `user_agent` VARCHAR(512) NOT NULL DEFAULT '' COMMENT '客户端浏览器User-Agent',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
  PRIMARY KEY (`id`),
  KEY `ix_operation_logs_user_id` (`user_id`),
  KEY `ix_operation_logs_username` (`username`),
  KEY `ix_operation_logs_module` (`module`),
  KEY `ix_operation_logs_action` (`action`),
  KEY `ix_operation_logs_status` (`status`),
  KEY `ix_operation_logs_created_at` (`created_at`),
  CONSTRAINT `fk_operation_logs_user_id`
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
    ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='系统操作日志表，记录用户登录、资料维护、工资计算、下载和系统管理动作';
