/**
 * Create Test Users for QA Audit
 * This script creates the test users needed for comprehensive QA testing
 */

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

// Load environment variables
dotenv.config();

const supabaseUrl = process.env.PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!supabaseUrl || !supabaseServiceKey) {
  console.error('❌ Missing required environment variables');
  console.error('Need: PUBLIC_SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY');
  process.exit(1);
}

// Create Supabase admin client
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
  auth: {
    autoRefreshToken: false,
    persistSession: false
  }
});

/**
 * Test users to create
 */
const TEST_USERS = [
  {
    email: 'admin@bct.com',
    password: 'password123',
    role: 'admin',
    name: 'Test Administrator'
  },
  {
    email: 'user@bct.com', 
    password: 'password123',
    role: 'user',
    name: 'Test User'
  }
];

/**
 * Create a test user
 */
async function createTestUser(userData) {
  console.log(`🔧 Creating test user: ${userData.email}`);
  
  try {
    // Create auth user
    const { data: authData, error: authError } = await supabase.auth.admin.createUser({
      email: userData.email,
      password: userData.password,
      email_confirm: true,
      user_metadata: {
        name: userData.name
      }
    });

    if (authError) {
      if (authError.message.includes('already registered')) {
        console.log(`⚠️  User ${userData.email} already exists, updating...`);
        
        // Try to update existing user
        const { data: existingUsers } = await supabase.auth.admin.listUsers();
        const existingUser = existingUsers.users.find(u => u.email === userData.email);
        
        if (existingUser) {
          // Update user metadata
          const { error: updateError } = await supabase.auth.admin.updateUserById(
            existingUser.id,
            {
              password: userData.password,
              user_metadata: {
                name: userData.name
              }
            }
          );
          
          if (updateError) {
            console.error(`❌ Failed to update user ${userData.email}:`, updateError.message);
            return false;
          }
          
          // Update database record
          await updateUserRecord(existingUser.id, userData);
          console.log(`✅ Updated existing user: ${userData.email}`);
          return true;
        }
      } else {
        console.error(`❌ Failed to create user ${userData.email}:`, authError.message);
        return false;
      }
    }

    if (authData.user) {
      // Create database record
      await createUserRecord(authData.user.id, userData);
      console.log(`✅ Created test user: ${userData.email}`);
      return true;
    }

  } catch (error) {
    console.error(`❌ Error creating user ${userData.email}:`, error.message);
    return false;
  }
  
  return false;
}

/**
 * Create user record in database
 */
async function createUserRecord(userId, userData) {
  // First, try to find an existing organization or create a test one
  let organizationId;
  
  // Look for existing organization
  const { data: existingOrgs } = await supabase
    .from('organizations')
    .select('id')
    .eq('name', 'Test Organization')
    .single();
    
  if (existingOrgs) {
    organizationId = existingOrgs.id;
  } else {
    // Create test organization
    const { data: newOrg, error: orgError } = await supabase
      .from('organizations')
      .insert({
        name: 'Test Organization',
        slug: 'test-org',
        created_at: new Date().toISOString()
      })
      .select('id')
      .single();
      
    if (orgError) {
      console.error('❌ Failed to create test organization:', orgError.message);
      // Use existing organization if creation fails
      const { data: anyOrg } = await supabase
        .from('organizations')
        .select('id')
        .limit(1)
        .single();
      organizationId = anyOrg?.id;
    } else {
      organizationId = newOrg.id;
    }
  }

  if (!organizationId) {
    console.error('❌ No organization available for user');
    return;
  }

  // Create user record
  const { error: userError } = await supabase
    .from('users')
    .upsert({
      id: userId,
      email: userData.email,
      role: userData.role,
      organization_id: organizationId,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    });

  if (userError) {
    console.error(`❌ Failed to create user record:`, userError.message);
  }
}

/**
 * Update existing user record
 */
async function updateUserRecord(userId, userData) {
  const { error } = await supabase
    .from('users')
    .update({
      role: userData.role,
      updated_at: new Date().toISOString()
    })
    .eq('id', userId);

  if (error) {
    console.error(`❌ Failed to update user record:`, error.message);
  }
}

/**
 * Main execution
 */
async function main() {
  console.log('🎯 Creating Test Users for QA Audit');
  console.log('📅 Date:', new Date().toISOString());
  
  let successCount = 0;
  
  for (const userData of TEST_USERS) {
    const success = await createTestUser(userData);
    if (success) {
      successCount++;
    }
    console.log(''); // Add spacing
  }
  
  console.log(`📊 Test User Creation Summary:`);
  console.log(`✅ Created/Updated: ${successCount}/${TEST_USERS.length}`);
  
  if (successCount === TEST_USERS.length) {
    console.log('🎉 All test users ready for QA testing!');
  } else {
    console.log('⚠️  Some test users failed to create. Check logs above.');
  }
}

// Run the script
main().catch(console.error);