-- 审计日志表
CREATE TABLE IF NOT EXISTS sys_audit_log (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID,
    username VARCHAR(64) NOT NULL,
    operation VARCHAR(128) NOT NULL,
    module VARCHAR(64) NOT NULL,
    action VARCHAR(64) NOT NULL,
    target_type VARCHAR(64),
    target_id VARCHAR(64),
    content TEXT,
    params TEXT,
    result TEXT,
    ip_address VARCHAR(64),
    user_agent VARCHAR(512),
    request_url VARCHAR(512),
    request_method VARCHAR(16),
    execution_time_ms INTEGER,
    status VARCHAR(16) DEFAULT 'SUCCESS',
    error_msg TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    tenant_id UUID
);

-- 创建索引
CREATE INDEX idx_audit_log_created_at ON sys_audit_log(created_at);
CREATE INDEX idx_audit_log_user_id ON sys_audit_log(user_id);
CREATE INDEX idx_audit_log_module ON sys_audit_log(module);
CREATE INDEX idx_audit_log_action ON sys_audit_log(action);
CREATE INDEX idx_audit_log_target ON sys_audit_log(target_type, target_id);

-- 归档表（结构相同，用于存储超过90天的数据）
CREATE TABLE IF NOT EXISTS sys_audit_log_archive (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID,
    username VARCHAR(64) NOT NULL,
    operation VARCHAR(128) NOT NULL,
    module VARCHAR(64) NOT NULL,
    action VARCHAR(64) NOT NULL,
    target_type VARCHAR(64),
    target_id VARCHAR(64),
    content TEXT,
    params TEXT,
    result TEXT,
    ip_address VARCHAR(64),
    user_agent VARCHAR(512),
    request_url VARCHAR(512),
    request_method VARCHAR(16),
    execution_time_ms INTEGER,
    status VARCHAR(16) DEFAULT 'SUCCESS',
    error_msg TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    tenant_id UUID
);

-- 为归档表创建索引
CREATE INDEX idx_audit_archive_created_at ON sys_audit_log_archive(created_at);
CREATE INDEX idx_audit_archive_user_id ON sys_audit_log_archive(user_id);
