import { deleteMember, handleNocoDbError } from '~/server/utils/nocodb';
import { createSessionManager } from '~/server/utils/session';

export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id');
  
  console.log('[api/members/[id].delete] =========================');
  console.log('[api/members/[id].delete] DELETE /api/members/' + id);
  console.log('[api/members/[id].delete] Request from:', getClientIP(event));
  
  if (!id) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Member ID is required'
    });
  }

  try {
    // Validate session and require Admin privileges (delete is more sensitive)
    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'
      });
    }

    const userTier = session.user.tier;
    if (userTier !== 'admin') {
      throw createError({
        statusCode: 403,
        statusMessage: 'Administrator privileges required to delete members'
      });
    }

    console.log('[api/members/[id].delete] Authorized user:', session.user.email, 'Tier:', userTier);

    // Delete member from NocoDB
    const result = await deleteMember(id);

    console.log('[api/members/[id].delete] ✅ Member deleted successfully:', id);

    return {
      success: true,
      data: { id },
      message: 'Member deleted successfully'
    };

  } catch (error: any) {
    console.error('[api/members/[id].delete] ❌ Error deleting member:', error);
    handleNocoDbError(error, 'deleteMember', 'Member');
  }
});
