import { createSessionManager } from '~/server/utils/session';

export default defineEventHandler(async (event) => {
  console.log('[api/admin/registration-config.post] =========================');
  console.log('[api/admin/registration-config.post] POST /api/admin/registration-config - Save registration configuration');
  
  try {
    // Validate session and require admin privileges
    const sessionManager = createSessionManager();
    const cookieHeader = getCookie(event, 'monacousa-session') ? getHeader(event, 'cookie') : undefined;
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session?.user) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Authentication required'
      });
    }

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

    console.log('[api/admin/registration-config.post] Authorized admin:', session.user.email);

    // Get and validate request body
    const body = await readBody(event);
    console.log('[api/admin/registration-config.post] Request body fields:', Object.keys(body));

    // Validate required fields
    const membershipFee = Number(body.membershipFee);
    if (!body.membershipFee || isNaN(membershipFee) || membershipFee <= 0) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Valid membership fee is required'
      });
    }

    if (!body.iban || typeof body.iban !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: 'IBAN is required'
      });
    }

    if (!body.accountHolder || typeof body.accountHolder !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: 'Account holder name is required'
      });
    }

    // Save registration configuration
    const { saveRegistrationConfig } = await import('~/server/utils/admin-config');
    await saveRegistrationConfig({
      membershipFee: membershipFee,
      iban: body.iban.trim(),
      accountHolder: body.accountHolder.trim()
    }, session.user.email);

    console.log('[api/admin/registration-config.post] ✅ Registration configuration saved successfully');

    return {
      success: true,
      message: 'Registration configuration saved successfully'
    };

  } catch (error: any) {
    console.error('[api/admin/registration-config.post] ❌ Error saving registration config:', error);
    throw error;
  }
});
