// server/api/admin/fix-event-attendee-counts.post.ts
import { createSessionManager } from '~/server/utils/session';
import { createNocoDBEventsClient } from '~/server/utils/nocodb-events';

export default defineEventHandler(async (event) => {
  try {
    console.log('[admin/fix-event-attendee-counts] Starting attendee count fix...');

    // Verify admin session
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    const session = sessionManager.getSession(cookieHeader);

    if (!session?.user || session.user.tier !== 'admin') {
      throw createError({
        statusCode: 403,
        statusMessage: 'Admin access required'
      });
    }

    console.log('[admin/fix-event-attendee-counts] Authorized admin user:', session.user.email);

    const eventsClient = createNocoDBEventsClient();

    // Get all events
    const eventsResponse = await eventsClient.findAll({ limit: 1000 });
    const events = eventsResponse.list || [];

    console.log('[admin/fix-event-attendee-counts] Found', events.length, 'events to process');

    const results = [];

    // Process each event
    for (const eventObj of events) {
      try {
        const eventId = eventObj.event_id || eventObj.id || (eventObj as any).Id;
        const eventTitle = eventObj.title || 'Unknown Event';
        
        console.log('[admin/fix-event-attendee-counts] Processing event:', eventTitle, 'ID:', eventId);

        // Force update the attendee count
        const newCount = await eventsClient.forceUpdateEventAttendeeCount(eventId.toString());
        
        results.push({
          event_id: eventId,
          title: eventTitle,
          old_count: eventObj.current_attendees || 0,
          new_count: newCount,
          status: 'success'
        });

        console.log('[admin/fix-event-attendee-counts] ✅ Fixed event:', eventTitle, 'Count:', newCount);

      } catch (eventError: any) {
        console.error('[admin/fix-event-attendee-counts] ❌ Error processing event:', eventObj.title, eventError);
        
        results.push({
          event_id: eventObj.event_id || eventObj.id,
          title: eventObj.title || 'Unknown Event',
          old_count: eventObj.current_attendees || 0,
          new_count: 0,
          status: 'error',
          error: eventError.message
        });
      }
    }

    const successCount = results.filter(r => r.status === 'success').length;
    const errorCount = results.filter(r => r.status === 'error').length;

    console.log('[admin/fix-event-attendee-counts] ✅ Fix completed. Success:', successCount, 'Errors:', errorCount);

    return {
      success: true,
      message: `Fixed attendee counts for ${successCount} events (${errorCount} errors)`,
      data: {
        total_events: events.length,
        success_count: successCount,
        error_count: errorCount,
        results: results
      }
    };

  } catch (error: any) {
    console.error('[admin/fix-event-attendee-counts] ❌ Error:', error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fix event attendee counts'
    });
  }
});
