// server/api/admin/rsvp-table-config.post.ts
import { createSessionManager } from '~/server/utils/session';
import { setEffectiveNocoDBConfig, getEffectiveNocoDBConfig } from '~/server/utils/admin-config';

export default defineEventHandler(async (event) => {
  try {
    console.log('[admin/rsvp-table-config] Configuring RSVP table...');

    // 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'
      });
    }

    const body = await readBody(event);
    const { rsvpTableId } = body;

    if (!rsvpTableId || typeof rsvpTableId !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: 'RSVP table ID is required'
      });
    }

    console.log('[admin/rsvp-table-config] Setting RSVP table ID:', rsvpTableId);

    // Get current configuration
    const currentConfig = getEffectiveNocoDBConfig() || {};
    
    // Update with RSVP table configuration
    const updatedConfig = {
      ...currentConfig,
      tables: {
        ...currentConfig.tables,
        event_rsvps: rsvpTableId,
        EventRSVPs: rsvpTableId // Also set the enum-style key for compatibility
      }
    };

    // Save updated configuration
    setEffectiveNocoDBConfig(updatedConfig);

    console.log('[admin/rsvp-table-config] ✅ RSVP table configuration updated successfully');

    return {
      success: true,
      message: 'RSVP table configuration updated successfully',
      data: {
        rsvpTableId,
        tables: updatedConfig.tables
      }
    };

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