import { sql } from '@vercel/postgres';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config({ path: '.env.local' });

async function addUserProfileColumns() {
  console.log('🔄 Adding user profile columns to users table...');

  try {
    // Add new columns to users table
    await sql`
      ALTER TABLE users 
      ADD COLUMN IF NOT EXISTS first_name VARCHAR(255),
      ADD COLUMN IF NOT EXISTS last_name VARCHAR(255),
      ADD COLUMN IF NOT EXISTS username VARCHAR(255) UNIQUE,
      ADD COLUMN IF NOT EXISTS profile_image_url TEXT
    `;

    console.log('✅ Successfully added user profile columns');

    // Update existing users with default values
    console.log('🔄 Updating existing users with default values...');
    
    const existingUsers = await sql`SELECT id, email FROM users WHERE first_name IS NULL`;
    
    for (const user of existingUsers.rows) {
      // Generate default values from email
      const emailPrefix = user.email.split('@')[0];
      const defaultUsername = `${emailPrefix}_${user.id}`;
      
      await sql`
        UPDATE users 
        SET 
          first_name = 'User',
          last_name = ${user.id.toString()},
          username = ${defaultUsername}
        WHERE id = ${user.id}
      `;
      
      console.log(`✅ Updated user ${user.email} with default values`);
    }

    console.log('✅ Migration completed successfully!');

  } catch (error) {
    console.error('❌ Error during migration:', error);
    throw error;
  }
}

// Run the migration
addUserProfileColumns()
  .then(() => {
    console.log('🎉 User profile columns migration completed!');
    process.exit(0);
  })
  .catch((error) => {
    console.error('💥 Migration failed:', error);
    process.exit(1);
  }); 