// server/api/admin/debug-rsvp-config.get.ts
import { createSessionManager } from '~/server/utils/session';
import { getEffectiveNocoDBConfig } from '~/server/utils/admin-config';
import { getEventTableId } from '~/server/utils/nocodb-events';

export default defineEventHandler(async (event) => {
  try {
    // 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/debug-rsvp-config] =========================');
    console.log('[admin/debug-rsvp-config] 🔍 DEBUG: RSVP Configuration Analysis');

    // Get effective config
    const effectiveConfig = getEffectiveNocoDBConfig();
    console.log('[admin/debug-rsvp-config] 🔍 Effective config:', JSON.stringify(effectiveConfig, null, 2));

    // Test RSVP table ID retrieval
    const rsvpTableId = getEventTableId('EventRSVPs');
    console.log('[admin/debug-rsvp-config] 🔍 RSVP Table ID retrieved:', rsvpTableId);

    // Test Events table ID retrieval
    const eventsTableId = getEventTableId('Events');
    console.log('[admin/debug-rsvp-config] 🔍 Events Table ID retrieved:', eventsTableId);

    return {
      success: true,
      debug: {
        effectiveConfig,
        rsvpTableId,
        eventsTableId,
        availableTableKeys: Object.keys(effectiveConfig?.tables || {}),
        rsvpTableInConfig: {
          'rsvps': effectiveConfig?.tables?.['rsvps'],
          'event_rsvps': effectiveConfig?.tables?.['event_rsvps'],
          'EventRSVPs': effectiveConfig?.tables?.['EventRSVPs'],
          'rsvp_table': effectiveConfig?.tables?.['rsvp_table'],
          'RSVPs': effectiveConfig?.tables?.['RSVPs']
        }
      }
    };

  } catch (error: any) {
    console.error('[admin/debug-rsvp-config] ❌ Error:', error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to debug RSVP configuration'
    });
  }
});
