// server/api/admin/backfill-event-ids.post.ts
export default defineEventHandler(async (event) => {
  console.log('[admin/backfill-event-ids] Starting event_id backfill process...');
  
  try {
    // Verify admin access
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session || session.user.tier !== 'admin') {
      throw createError({
        statusCode: 403,
        statusMessage: 'Admin access required'
      });
    }

    console.log(`[admin/backfill-event-ids] Admin access verified for user: ${session.user.email}`);

    const { createNocoDBEventsClient } = await import('~/server/utils/nocodb-events');
    const eventsClient = createNocoDBEventsClient();
    
    // Get all events
    const response = await eventsClient.findAll({ limit: 1000 });
    const events = response.list || [];
    
    console.log(`[admin/backfill-event-ids] Found ${events.length} events to process`);
    
    const results = {
      processed: 0,
      updated: 0,
      skipped: 0,
      errors: 0,
      details: [] as any[]
    };
    
    for (const eventItem of events) {
      results.processed++;
      const eventId = (eventItem as any).Id;
      
      try {
        // Check if event_id already exists
        if (eventItem.event_id && eventItem.event_id.trim() !== '') {
          console.log(`[admin/backfill-event-ids] Event ${eventId} already has event_id: ${eventItem.event_id}`);
          results.skipped++;
          results.details.push({
            id: eventId,
            title: eventItem.title,
            status: 'skipped',
            reason: 'Already has event_id',
            existing_event_id: eventItem.event_id
          });
          continue;
        }
        
        // Generate unique event_id based on event date and title
        const eventDate = new Date(eventItem.start_datetime);
        const dateString = eventDate.toISOString().split('T')[0].replace(/-/g, ''); // YYYYMMDD
        const timeString = eventDate.toISOString().split('T')[1].split(':').slice(0,2).join(''); // HHMM
        const titleSlug = eventItem.title.toLowerCase().replace(/[^a-z0-9]/g, '').substring(0, 8);
        
        const newEventId = `evt_${dateString}_${timeString}_${titleSlug}`;
        
        console.log(`[admin/backfill-event-ids] Updating event ${eventId} (${eventItem.title}) with event_id: ${newEventId}`);
        
        // Update the event with the new event_id
        await eventsClient.update(eventId.toString(), { event_id: newEventId });
        
        results.updated++;
        results.details.push({
          id: eventId,
          title: eventItem.title,
          status: 'updated',
          new_event_id: newEventId
        });
        
      } catch (updateError: any) {
        console.error(`[admin/backfill-event-ids] Error updating event ${eventId}:`, updateError);
        results.errors++;
        results.details.push({
          id: eventId,
          title: eventItem.title,
          status: 'error',
          error: updateError.message || 'Update failed'
        });
      }
    }
    
    console.log(`[admin/backfill-event-ids] Backfill completed. Processed: ${results.processed}, Updated: ${results.updated}, Skipped: ${results.skipped}, Errors: ${results.errors}`);
    
    return {
      success: true,
      message: `Event ID backfill completed successfully`,
      data: results
    };
    
  } catch (error: any) {
    console.error('[admin/backfill-event-ids] Backfill process failed:', error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Event ID backfill failed'
    });
  }
});
