import { getDB } from "./db.ts";
import fs from "fs";
import path from "path";

/**
 * Execute database migrations from SQL files
 * Run this script to set up all required tables for training, admin, and games
 */
export async function executeMigrations() {
  try {
    const db = await getDB();
    if (!db) {
      console.error("Failed to connect to database");
      return false;
    }

    const migrationsDir = path.join(process.cwd(), "migrations");
    const migrationFiles = [
      "training_tables.sql",
      "admin_tables.sql",
    ];

    for (const file of migrationFiles) {
      const filePath = path.join(migrationsDir, file);
      
      if (!fs.existsSync(filePath)) {
        console.warn(`Migration file not found: ${filePath}`);
        continue;
      }

      const sql = fs.readFileSync(filePath, "utf-8");
      const statements = sql.split(";").filter(s => s.trim());

      console.log(`Executing migration: ${file}`);
      
      for (const statement of statements) {
        if (statement.trim()) {
          try {
            await db.execute(statement);
            console.log(`✓ Executed: ${statement.substring(0, 50)}...`);
          } catch (error) {
            console.error(`✗ Failed to execute statement: ${error}`);
            // Continue with next statement
          }
        }
      }
    }

    console.log("✓ All migrations completed successfully");
    return true;
  } catch (error) {
    console.error("Migration execution failed:", error);
    return false;
  }
}

// Run migrations if this file is executed directly
if (require.main === module) {
  executeMigrations().then(success => {
    process.exit(success ? 0 : 1);
  });
}

export default executeMigrations;
