#!/usr/bin/env node

import { createClient } from '@supabase/supabase-js';
import { config } from 'dotenv';

// Load environment variables
config();

const supabaseUrl = process.env.SUPABASE_URL || process.env.PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY;

if (!supabaseUrl || !supabaseServiceKey) {
  console.error('Missing required environment variables: SUPABASE_URL and SUPABASE_SERVICE_KEY');
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseServiceKey);

async function promoteUserToAdmin() {
  const email = process.argv[2];
  
  if (!email) {
    console.error('Usage: node promote-to-admin.js <email>');
    process.exit(1);
  }

  try {
    console.log(`Promoting ${email} to admin...`);
    
    // First, find the user
    const { data: users, error: userError } = await supabase.auth.admin.listUsers();
    if (userError) throw userError;
    
    const user = users.users.find(u => u.email === email);
    if (!user) {
      console.error(`User with email ${email} not found`);
      process.exit(1);
    }
    
    // Update user role to admin
    const { error: updateError } = await supabase
      .from('users')
      .upsert({
        id: user.id,
        email: user.email,
        role: 'admin'
      });
      
    if (updateError) throw updateError;
    
    console.log(`✅ Successfully promoted ${email} to admin!`);
    console.log(`User ID: ${user.id}`);
    
  } catch (error) {
    console.error('Error promoting user to admin:', error);
    process.exit(1);
  }
}

promoteUserToAdmin();