import type { NocoDBSettings } from '~/utils/types';

export default defineEventHandler(async (event) => {
  console.log('[api/admin/nocodb-config.get] =========================');
  console.log('[api/admin/nocodb-config.get] GET /api/admin/nocodb-config');
  console.log('[api/admin/nocodb-config.get] Request from:', getClientIP(event));

  try {
    // Check admin authorization
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    const session = sessionManager.getSession(cookieHeader);

    if (!session?.user) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Authentication required'
      });
    }

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

    console.log('[api/admin/nocodb-config.get] Admin access confirmed for:', session.user.email);

    // Get current configuration using the new admin config system
    const { getCurrentConfig } = await import('~/server/utils/admin-config');
    const settings = await getCurrentConfig();

    console.log('[api/admin/nocodb-config.get] ✅ Settings retrieved successfully');

    return {
      success: true,
      data: settings
    };

  } catch (error: any) {
    console.error('[api/admin/nocodb-config.get] ❌ Error:', error);
    
    if (error.statusCode) {
      throw error; // Re-throw HTTP errors
    }

    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to retrieve NocoDB configuration'
    });
  }
});
