-- ============================================
-- TJWater Server 审计日志表迁移脚本
-- ============================================

-- 创建审计日志表
CREATE TABLE IF NOT EXISTS audit_logs (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
    username VARCHAR(50),
    action VARCHAR(50) NOT NULL,
    resource_type VARCHAR(50),
    resource_id VARCHAR(100),
    ip_address VARCHAR(45),
    user_agent TEXT,
    request_method VARCHAR(10),
    request_path TEXT,
    request_data JSONB,
    response_status INTEGER,
    error_message TEXT,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL
);

-- 创建索引以提高查询性能
CREATE INDEX IF NOT EXISTS idx_audit_logs_user_id ON audit_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_audit_logs_username ON audit_logs(username);
CREATE INDEX IF NOT EXISTS idx_audit_logs_timestamp ON audit_logs(timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_audit_logs_action ON audit_logs(action);
CREATE INDEX IF NOT EXISTS idx_audit_logs_resource ON audit_logs(resource_type, resource_id);

-- 添加注释
COMMENT ON TABLE audit_logs IS '审计日志表 - 记录所有关键操作';
COMMENT ON COLUMN audit_logs.id IS '日志ID（主键）';
COMMENT ON COLUMN audit_logs.user_id IS '用户ID（外键）';
COMMENT ON COLUMN audit_logs.username IS '用户名（冗余字段，用于用户删除后仍可查询）';
COMMENT ON COLUMN audit_logs.action IS '操作类型（如：LOGIN, LOGOUT, CREATE, UPDATE, DELETE）';
COMMENT ON COLUMN audit_logs.resource_type IS '资源类型（如：user, project, network）';
COMMENT ON COLUMN audit_logs.resource_id IS '资源ID';
COMMENT ON COLUMN audit_logs.ip_address IS '客户端IP地址';
COMMENT ON COLUMN audit_logs.user_agent IS '客户端User-Agent';
COMMENT ON COLUMN audit_logs.request_method IS 'HTTP请求方法';
COMMENT ON COLUMN audit_logs.request_path IS '请求路径';
COMMENT ON COLUMN audit_logs.request_data IS '请求数据（JSON格式，敏感信息已脱敏）';
COMMENT ON COLUMN audit_logs.response_status IS 'HTTP响应状态码';
COMMENT ON COLUMN audit_logs.error_message IS '错误消息（如果有）';
COMMENT ON COLUMN audit_logs.timestamp IS '操作时间';
