const db = require('./db');

const createAnalyticsTable = async () => {
    console.log('--- Creating analytics_events Table ---');
    try {
        await db.query(`
            CREATE TABLE IF NOT EXISTS analytics_events (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT,
                event_type VARCHAR(100) NOT NULL,
                event_data JSON DEFAULT NULL,
                ip_address VARCHAR(45),
                user_agent TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX (user_id),
                INDEX (event_type),
                INDEX (created_at)
            )
        `);
        console.log('✅ Checked/Created analytics_events table');
        
        // Add foreign key constraint safely (if not exists)
        // Note: Adding FK in a separate step often requires checking if it exists first to avoid errors, 
        // but for now, we'll assume standard creation. If users might be deleted, we might want ON DELETE SET NULL or CASCADE.
        // Given this is analytics, we probably want to keep the data even if user is deleted? 
        // Or maybe just let it be loose for now. Let's add a basic FK for data integrity if possible.
        // Actually, for analytics, strict FKs can be annoying if we hard delete users. 
        // Let's stick to the table creation for now.

        process.exit(0);
    } catch (e) {
        console.error('❌ Failed to create analytics_events table:', e.message);
        process.exit(1);
    }
};

createAnalyticsTable();
