/**
 * Test script for staff dashboard demos API
 * Tests the fixed Supabase integration
 */

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

const supabaseUrl = 'http://localhost:54321';
const supabaseServiceKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';

console.log('🔧 Testing Supabase Demo Bookings Integration\n');

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

try {
  // Test 1: Fetch all bookings
  console.log('📋 Test 1: Fetching all demo bookings...');
  const { data: allBookings, error: allError } = await supabaseAdmin
    .from('demo_bookings')
    .select('*')
    .order('created_at', { ascending: false })
    .limit(100);

  if (allError) {
    console.error('❌ Error fetching bookings:', allError);
  } else {
    console.log(`✅ Found ${allBookings?.length || 0} bookings`);
    if (allBookings && allBookings.length > 0) {
      console.log('\n   Sample booking:');
      const sample = allBookings[0];
      console.log(`   - ID: ${sample.id}`);
      console.log(`   - Name: ${sample.full_name}`);
      console.log(`   - Email: ${sample.email}`);
      console.log(`   - Status: ${sample.status}`);
      console.log(`   - Created: ${sample.created_at}`);
    }
  }

  // Test 2: Filter by status
  console.log('\n📋 Test 2: Filtering by status (pending)...');
  const { data: pendingBookings, error: pendingError } = await supabaseAdmin
    .from('demo_bookings')
    .select('*')
    .eq('status', 'pending')
    .order('created_at', { ascending: false });

  if (pendingError) {
    console.error('❌ Error filtering:', pendingError);
  } else {
    console.log(`✅ Found ${pendingBookings?.length || 0} pending bookings`);
  }

  // Test 3: Search functionality
  console.log('\n📋 Test 3: Testing search (email contains "test")...');
  const { data: searchResults, error: searchError } = await supabaseAdmin
    .from('demo_bookings')
    .select('*')
    .or('full_name.ilike.%test%,email.ilike.%test%')
    .order('created_at', { ascending: false });

  if (searchError) {
    console.error('❌ Error searching:', searchError);
  } else {
    console.log(`✅ Found ${searchResults?.length || 0} matching bookings`);
  }

  // Test 4: Check new staff fields
  console.log('\n📋 Test 4: Verifying staff management fields exist...');
  if (allBookings && allBookings.length > 0) {
    const fields = Object.keys(allBookings[0]);
    const staffFields = ['meeting_link', 'internal_notes', 'contacted_at', 'contacted_by'];
    const missingFields = staffFields.filter(f => !fields.includes(f));

    if (missingFields.length === 0) {
      console.log('✅ All staff fields present:', staffFields.join(', '));
    } else {
      console.log('⚠️  Missing fields:', missingFields.join(', '));
    }
  }

  console.log('\n✅ All tests completed successfully!');
  console.log('\n📝 Summary:');
  console.log(`   - Total bookings: ${allBookings?.length || 0}`);
  console.log(`   - Pending: ${pendingBookings?.length || 0}`);
  console.log(`   - Search results: ${searchResults?.length || 0}`);
  console.log(`   - Database: Supabase (localhost:54321)`);
  console.log(`   - Table: demo_bookings`);

} catch (error) {
  console.error('\n❌ Test failed with error:', error);
  process.exit(1);
}
