#!/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');
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseServiceKey);

async function testAuth() {
  console.log('Testing authentication...');
  
  // Test user creation and admin setup
  const testEmail = 'tmartinez@gmail.com';
  const testPassword = 'testpassword123';
  
  try {
    // Create test user if doesn't exist
    console.log(`Creating/updating test user: ${testEmail}`);
    
    let userId;
    
    // Try to get existing user
    const { data: existingUsers } = await supabase.auth.admin.listUsers();
    const existingUser = existingUsers.users.find(u => u.email === testEmail);
    
    if (existingUser) {
      console.log('User already exists:', existingUser.id);
      userId = existingUser.id;
    } else {
      // Create new user
      const { data: newUser, error: createError } = await supabase.auth.admin.createUser({
        email: testEmail,
        password: testPassword,
        email_confirm: true
      });
      
      if (createError) throw createError;
      userId = newUser.user.id;
      console.log('Created new user:', userId);
    }
    
    // Ensure user record exists in database with admin role
    const { error: upsertError } = await supabase
      .from('users')
      .upsert({
        id: userId,
        email: testEmail,
        role: 'admin'
      });
    
    if (upsertError) throw upsertError;
    
    console.log('✅ Test user setup complete');
    console.log(`Email: ${testEmail}`);
    console.log(`Password: ${testPassword}`);
    console.log('You can now test login at http://localhost:4322/login');
    
  } catch (error) {
    console.error('Error setting up test user:', error);
  }
}

testAuth().catch(console.error);