const { createClient } = require('@supabase/supabase-js');
require('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('  - PUBLIC_SUPABASE_URL');
  console.error('  - SUPABASE_SERVICE_ROLE_KEY');
  process.exit(1);
}

console.log('🔑 Environment variables found');
console.log('Supabase URL:', supabaseUrl);

const supabase = createClient(supabaseUrl, supabaseServiceKey, {
  auth: {
    autoRefreshToken: false,
    persistSession: false
  }
});

async function createTestUser() {
  const testEmail = 'tmartinez@gmail.com';
  const testPassword = 'TestPassword123!';
  
  console.log('\n🧪 Creating test user...');
  console.log('Email:', testEmail);
  
  try {
    // Step 1: Create user in Supabase Auth
    console.log('\n1️⃣ Creating auth user...');
    const { data: authData, error: authError } = await supabase.auth.admin.createUser({
      email: testEmail,
      password: testPassword,
      email_confirm: true, // Skip email confirmation
      user_metadata: {
        name: 'Tyler Martinez'
      }
    });
    
    if (authError) {
      if (authError.message.includes('already been registered')) {
        console.log('✓ User already exists in auth system');
        
        // List users to find the existing user
        const { data: usersData, error: listError } = await supabase.auth.admin.listUsers();
        if (listError) {
          console.error('❌ Error listing users:', listError);
          return;
        }
        
        const existingAuthUser = usersData.users.find(u => u.email === testEmail);
        if (!existingAuthUser) {
          console.error('❌ Could not find existing user');
          return;
        }
        
        console.log('✓ Found existing user:', existingAuthUser.id);
        
        // Update password for testing
        const { error: updateError } = await supabase.auth.admin.updateUserById(existingAuthUser.id, {
          password: testPassword
        });
        
        if (updateError) {
          console.log('⚠️  Could not update password:', updateError.message);
        } else {
          console.log('✓ Updated password for testing');
        }
        
      } else {
        console.error('❌ Auth creation error:', authError);
        return;
      }
    } else {
      console.log('✓ Auth user created:', authData.user.id);
    }
    
    // Step 2: Check/create organization
    console.log('\n2️⃣ Setting up organization...');
    let organizationId;
    
    const { data: existingOrg, error: orgError } = await supabase
      .from('organizations')
      .select('id, name')
      .limit(1)
      .single();
    
    if (orgError || !existingOrg) {
      console.log('Creating test organization...');
      const { data: newOrg, error: createOrgError } = await supabase
        .from('organizations')
        .insert({
          name: 'Test Organization',
          created_at: new Date().toISOString()
        })
        .select()
        .single();
      
      if (createOrgError) {
        console.error('❌ Error creating organization:', createOrgError);
        return;
      }
      
      organizationId = newOrg.id;
      console.log('✓ Created organization:', organizationId);
    } else {
      organizationId = existingOrg.id;
      console.log('✓ Using existing organization:', existingOrg.name, '(' + organizationId + ')');
    }
    
    // Step 3: Check/create user record
    console.log('\n3️⃣ Setting up user record...');
    
    const { data: existingUser, error: userCheckError } = await supabase
      .from('users')
      .select('id, email, role, organization_id')
      .eq('email', testEmail)
      .single();
    
    if (userCheckError && userCheckError.code !== 'PGRST116') {
      console.error('❌ Error checking user:', userCheckError);
      return;
    }
    
    if (!existingUser) {
      console.log('Creating user record...');
      const { data: newUser, error: createUserError } = await supabase
        .from('users')
        .insert({
          email: testEmail,
          name: 'Tyler Martinez',
          role: 'admin',
          organization_id: organizationId
        })
        .select()
        .single();
      
      if (createUserError) {
        console.error('❌ Error creating user record:', createUserError);
        return;
      }
      
      console.log('✓ Created user record:', newUser.id);
    } else {
      console.log('✓ User record exists:', existingUser.id);
      
      // Update organization if needed
      if (!existingUser.organization_id) {
        const { error: updateError } = await supabase
          .from('users')
          .update({ 
            organization_id: organizationId,
            role: 'admin'
          })
          .eq('email', testEmail);
        
        if (updateError) {
          console.error('❌ Error updating user:', updateError);
          return;
        }
        
        console.log('✓ Updated user with organization');
      }
    }
    
    // Step 4: Create test event
    console.log('\n4️⃣ Creating test event...');
    
    const { data: existingEvent, error: eventCheckError } = await supabase
      .from('events')
      .select('id, title, slug')
      .eq('id', '7ac12bd2-8509-4db3-b1bc-98a808646311')
      .single();
    
    if (eventCheckError && eventCheckError.code !== 'PGRST116') {
      console.log('Creating test event...');
      
      const { data: userRecord } = await supabase
        .from('users')
        .select('id')
        .eq('email', testEmail)
        .single();
      
      if (userRecord) {
        const { data: newEvent, error: createEventError } = await supabase
          .from('events')
          .insert({
            id: '7ac12bd2-8509-4db3-b1bc-98a808646311',
            title: 'Test Event for Debug',
            slug: 'test-event-debug',
            venue: 'Test Venue',
            start_time: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // Tomorrow
            description: 'Test event for debugging authentication',
            created_by: userRecord.id,
            organization_id: organizationId
          })
          .select()
          .single();
        
        if (createEventError) {
          console.log('⚠️  Could not create test event:', createEventError.message);
        } else {
          console.log('✓ Created test event:', newEvent.id);
        }
      }
    } else {
      console.log('✓ Test event already exists:', existingEvent.title);
    }
    
    console.log('\n🎉 Test user setup complete!');
    console.log('=====================================');
    console.log('Test credentials:');
    console.log('  Email:', testEmail);
    console.log('  Password:', testPassword);
    console.log('  Organization:', organizationId);
    console.log('  Role: admin');
    console.log('\nYou can now test login with these credentials.');
    
  } catch (error) {
    console.error('💥 Unexpected error:', error);
  }
}

createTestUser();