#!/usr/bin/env node

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

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

async function promoteUserToAdmin(email) {
  if (!email) {
    console.error('❌ Error: Email is required');
    console.log('Usage: node scripts/promote-user-to-admin.js <email>');
    console.log('Example: node scripts/promote-user-to-admin.js user@example.com');
    process.exit(1);
  }

  try {
    console.log('🔍 Looking for user:', email);
    
    // Check if user exists
    const userCheck = await sql`
      SELECT id, email, role FROM users WHERE email = ${email}
    `;

    if (userCheck.rows.length === 0) {
      console.error('❌ User not found:', email);
      console.log('💡 Make sure the user has registered first');
      process.exit(1);
    }

    const user = userCheck.rows[0];
    console.log('👤 Found user:', {
      id: user.id,
      email: user.email,
      currentRole: user.role
    });

    if (user.role === 'admin') {
      console.log('✅ User is already an admin!');
      process.exit(0);
    }

    // Promote user to admin
    const result = await sql`
      UPDATE users 
      SET role = 'admin' 
      WHERE email = ${email}
      RETURNING id, email, role, created_at
    `;

    if (result.rows.length > 0) {
      const updatedUser = result.rows[0];
      console.log('🎉 Successfully promoted user to admin!');
      console.log('👑 Updated user details:', {
        id: updatedUser.id,
        email: updatedUser.email,
        role: updatedUser.role,
        created_at: updatedUser.created_at
      });
      console.log('');
      console.log('🔐 The user can now access admin features at:');
      console.log('   • /admin/card-editor');
      console.log('   • /admin/card-import');
    } else {
      console.error('❌ Failed to promote user');
    }

  } catch (error) {
    console.error('❌ Database error:', error.message);
    process.exit(1);
  }
}

// Get email from command line arguments
const email = process.argv[2];
promoteUserToAdmin(email); 