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

const runMigration = async () => {
    try {
        console.log('🔄 Creating Lesson tables...');

        const sqlPath = path.join(__dirname, 'create_lesson_tables.sql');
        const sql = fs.readFileSync(sqlPath, 'utf8');

        // Split by semicolon and execute each statement
        const statements = sql.split(';').filter(stmt => stmt.trim().length > 0);

        for (const statement of statements) {
            await db.query(statement);
        }

        console.log('✅ Lesson tables created successfully!');

        console.log('🔄 Seeding sample lesson data...');
        const seedPath = path.join(__dirname, 'seed_sample_lessons.sql');
        const seedSql = fs.readFileSync(seedPath, 'utf8');

        const seedStatements = seedSql.split(';').filter(stmt => stmt.trim().length > 0);

        for (const statement of seedStatements) {
            await db.query(statement);
        }

        console.log('✅ Sample lesson data inserted successfully!');
        console.log('🎉 Lesson system is ready!');

        process.exit(0);
    } catch (error) {
        console.error('❌ Migration failed:', error);
        process.exit(1);
    }
};

runMigration();
