import { supabase } from '@/integrations/supabase/client';

/**
 * Diagnostic utility to verify Blocked Dates functionality
 */
export async function runBlockedDatesDiagnostic() {
  console.group('🔍 BLOCKED DATES DIAGNOSTIC REPORT');
  const logs = [];
  const log = (msg, data = null) => {
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = `[${timestamp}] ${msg}`;
    console.log(logEntry, data || '');
    logs.push({ message: logEntry, data });
  };

  try {
    log('STEP 1: Checking client_date_requests table for approved records...');
    
    const { data: approvedRequests, error: queryError } = await supabase
      .from('client_date_requests')
      .select('id, client_id, requested_date, status, task_description')
      .eq('status', 'approved');

    if (queryError) {
      log('❌ ERROR: Failed to query client_date_requests table', queryError);
      throw queryError;
    }

    log(`Found ${approvedRequests.length} approved requests in database.`);
    
    const uniqueClients = [...new Set(approvedRequests.map(r => r.client_id))];
    log(`Unique Clients involved in approved requests: ${uniqueClients.length}`, uniqueClients);
    
    if (approvedRequests.length > 0) {
        log('Sample Data Structure:', approvedRequests[0]);
    }

    log('STEP 2: Testing get_blocked_dates_client RPC function...');
    
    const { data: rpcDataAll, error: rpcErrorAll } = await supabase.rpc('get_blocked_dates_client', { p_client_id: null });

    if (rpcErrorAll) {
      log('❌ RPC CALL FAILED (No Filter):', rpcErrorAll);
    } else {
      log(`✅ RPC Success (No Filter). Returned ${rpcDataAll?.length || 0} dates.`);
      if (rpcDataAll && rpcDataAll.length > 0) {
        log('RPC Sample Data:', rpcDataAll.slice(0, 3));
      }
    }

    if (approvedRequests.length === 0) {
       log('⚠️ WARNING: No approved requests found. Attempting to seed test data for validation...');
       
       const { data: clients, error: clientError } = await supabase
         .from('clients')
         .select('id, name')
         .limit(5);
         
       if (clientError || !clients || clients.length === 0) {
          log('❌ CRITICAL: Cannot seed data - No clients found in database.');
       } else {
          log(`Found ${clients.length} clients to use for seeding.`);
          
          const today = new Date();
          const testRequests = [];
          
          for(let i = 0; i < 3; i++) {
             const client = clients[i % clients.length];
             const futureDate = new Date(today);
             futureDate.setDate(today.getDate() + 5 + i);
             const dateStr = futureDate.toISOString().split('T')[0];
             
             testRequests.push({
                client_id: client.id,
                requested_date: dateStr,
                task_description: `Diagnostic Auto-Generated Test Request (${i+1})`,
                status: 'approved',
                approved_at: new Date().toISOString(),
                requested_at: new Date().toISOString()
             });
          }

          log('Attempting to insert test requests:', testRequests);
          
          const { error: insertError } = await supabase
            .from('client_date_requests')
            .insert(testRequests);
            
          if (insertError) {
             log('❌ Failed to insert test data:', insertError);
          } else {
             log('✅ Successfully inserted test data.');
             
             log('STEP 3.1: Re-verifying RPC after seeding...');
             const { data: newData } = await supabase.rpc('get_blocked_dates_client', { p_client_id: null });
             log(`✅ Re-verification Result: RPC now returns ${newData?.length || 0} dates.`);
          }
       }
    } else {
        log('ℹ️ Skipping seeding (Data already exists).');
    }

    log('📊 DIAGNOSTIC COMPLETE');
    if (approvedRequests.length > 0 || (rpcDataAll && rpcDataAll.length > 0)) {
        log('RESULT: Blocked dates system appears to have data accessible.');
    } else {
        log('RESULT: System empty or inaccessible.');
    }

  } catch (err) {
    log('❌ UNEXPECTED ERROR during diagnostic:', err);
  } finally {
    console.groupEnd();
  }
  
  return logs;
}
