const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');

// Parse connection string from environment or command line
const connectionString = process.env.DATABASE_URL || process.argv[2];

if (!connectionString) {
  console.error('Please provide DATABASE_URL as environment variable or command line argument');
  console.error('Example: node run-migration.js "postgresql://user:pass@host:port/db"');
  process.exit(1);
}

const pool = new Pool({
  connectionString,
  ssl: {
    rejectUnauthorized: false // For AWS RDS
  }
});

async function runMigration() {
  try {
    // Read the migration file
    const migrationPath = path.join(__dirname, '../database/migrations/004_remove_brand_column.sql');
    const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
    
    console.log('Running migration: 004_remove_brand_column.sql');
    console.log('SQL:', migrationSQL);
    
    // Execute the migration
    await pool.query(migrationSQL);
    
    console.log('✅ Migration completed successfully!');
    
    // Verify the column was removed
    const result = await pool.query(`
      SELECT column_name 
      FROM information_schema.columns 
      WHERE table_name = 'filaments' 
      AND column_name = 'brand'
    `);
    
    if (result.rows.length === 0) {
      console.log('✅ Verified: brand column has been removed');
    } else {
      console.log('⚠️  Warning: brand column still exists');
    }
    
  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    process.exit(1);
  } finally {
    await pool.end();
  }
}

runMigration();