#!/usr/bin/env node

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

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

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

  try {
    console.log('🔍 Looking for admin 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);
      process.exit(1);
    }

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

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

    if (user.role !== 'admin') {
      console.error('❌ User is not an admin, cannot demote');
      process.exit(1);
    }

    // Check if this is the last admin
    const adminCount = await sql`
      SELECT COUNT(*) as count FROM users WHERE role = 'admin'
    `;

    if (parseInt(adminCount.rows[0].count) <= 1) {
      console.error('❌ Cannot demote the last admin user!');
      console.log('💡 Make sure there is at least one admin before demoting');
      process.exit(1);
    }

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

    if (result.rows.length > 0) {
      const updatedUser = result.rows[0];
      console.log('✅ Successfully demoted admin to user!');
      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 no longer has access to admin features');
    } else {
      console.error('❌ Failed to demote user');
    }

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

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