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

export default defineEventHandler(async (event) => {
  console.log('[api/admin/nocodb-config.post] =========================');
  console.log('[api/admin/nocodb-config.post] POST /api/admin/nocodb-config');
  console.log('[api/admin/nocodb-config.post] 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.post] Admin access confirmed for:', session.user.email);

    // Get request body
    const body = await readBody(event) as NocoDBSettings;
    
    // Validate required fields
    if (!body.url || !body.apiKey || !body.baseId || !body.tables) {
      throw createError({
        statusCode: 400,
        statusMessage: 'All fields are required: url, apiKey, baseId, tables'
      });
    }

    // Validate URL format
    if (!body.url.startsWith('http://') && !body.url.startsWith('https://')) {
      throw createError({
        statusCode: 400,
        statusMessage: 'URL must start with http:// or https://'
      });
    }

    console.log('[api/admin/nocodb-config.post] Saving NocoDB configuration...');
    console.log('[api/admin/nocodb-config.post] URL:', body.url);
    console.log('[api/admin/nocodb-config.post] Base ID:', body.baseId);
    console.log('[api/admin/nocodb-config.post] Tables:', Object.keys(body.tables));
    console.log('[api/admin/nocodb-config.post] API Key: [REDACTED]');

    // Save configuration using the new admin config system
    const { saveAdminConfig } = await import('~/server/utils/admin-config');
    await saveAdminConfig(body, session.user.email);

    console.log('[api/admin/nocodb-config.post] ✅ Configuration saved successfully');

    return {
      success: true,
      message: 'NocoDB configuration saved successfully and will be applied immediately'
    };

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

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