const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../.env') });
const db = require('../db');

async function createAuditTable() {
    const client = await db.pool.connect();
    try {
        console.log('正在创建 audit_logs 表...');
        await client.query(`
            CREATE TABLE IF NOT EXISTS audit_logs (
                id SERIAL PRIMARY KEY,
                user_id INTEGER REFERENCES users(id),
                username VARCHAR(50),
                real_name VARCHAR(50),
                ip_address VARCHAR(50),
                method VARCHAR(10),
                url TEXT,
                description VARCHAR(255),
                status INTEGER,
                duration INTEGER,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
        `);
        
        console.log('正在创建索引...');
        await client.query('CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at ON audit_logs(created_at DESC);');
        await client.query('CREATE INDEX IF NOT EXISTS idx_audit_logs_username ON audit_logs(username);');
        
        console.log('audit_logs 表创建成功！');
    } catch (err) {
        console.error('创建表失败:', err);
    } finally {
        client.release();
        process.exit();
    }
}

createAuditTable();
