import { deleteProfileImage, removeMemberProfileImageUrl } from '~/server/utils/profile-images';

// Authentication utility - we'll need to check if it exists
async function requireAuth(event: any) {
  // Check for session-based authentication
  const sessionCookie = getCookie(event, 'auth-token') || getCookie(event, 'nuxt-oidc-auth-session');
  
  if (!sessionCookie) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Authentication required',
    });
  }

  // For now, return a basic user object - this should integrate with your existing auth system
  const user = event.context.user;
  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Invalid authentication',
    });
  }
  
  return user;
}

// Role-based access control
function canEditMember(user: any, targetMemberId: string): boolean {
  // Admin can edit anyone
  if (user.tier === 'admin' || user.groups?.includes('admin') || user.groups?.includes('monaco-admin')) {
    return true;
  }
  
  // Board members can edit anyone
  if (user.tier === 'board' || user.groups?.includes('board') || user.groups?.includes('monaco-board')) {
    return true;
  }
  
  // Users can only edit their own profile
  return user.email === targetMemberId || user.member_id === targetMemberId;
}

export default defineEventHandler(async (event) => {
  try {
    // Check authentication
    const user = await requireAuth(event);
    
    // Get route parameter
    const memberId = getRouterParam(event, 'memberId');
    
    if (!memberId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Member ID is required',
      });
    }
    
    // Check permissions
    if (!canEditMember(user, memberId)) {
      throw createError({
        statusCode: 403,
        statusMessage: 'You can only delete your own profile image',
      });
    }
    
    console.log(`[profile-delete] Deleting profile image for member: ${memberId}`);
    
    // Delete image files from MinIO
    await deleteProfileImage(memberId);
    
    // Remove image reference from database
    await removeMemberProfileImageUrl(memberId);
    
    console.log(`[profile-delete] Successfully deleted profile image for member: ${memberId}`);
    
    return {
      success: true,
      message: 'Profile image deleted successfully',
      memberId,
    };
    
  } catch (error: any) {
    console.error('[profile-delete] Delete failed:', error);
    
    if (error.statusCode) {
      throw error; // Re-throw HTTP errors
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to delete profile image',
    });
  }
});
