import { getProfileImageUrl } from '~/server/utils/profile-images';

export default defineEventHandler(async (event) => {
  try {
    // Get route parameters
    const memberId = getRouterParam(event, 'memberId');
    const size = getRouterParam(event, 'size') as 'original' | 'small' | 'medium';
    
    if (!memberId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Member ID is required',
      });
    }
    
    // Validate size parameter
    const validSizes = ['original', 'small', 'medium'];
    if (!validSizes.includes(size)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Invalid size. Must be one of: original, small, medium',
      });
    }
    
    console.log(`[profile-image] Getting image URL for member: ${memberId}, size: ${size}`);
    
    // Get presigned URL for the image
    const imageUrl = await getProfileImageUrl(memberId, size);
    
    if (!imageUrl) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Profile image not found',
      });
    }
    
    // Set cache headers for better performance
    setHeader(event, 'Cache-Control', 'public, max-age=300'); // 5 minutes
    setHeader(event, 'Content-Type', 'application/json');
    
    return {
      success: true,
      imageUrl,
      memberId,
      size,
      expiresIn: 3600, // URLs expire in 1 hour
    };
    
  } catch (error: any) {
    console.error('[profile-image] Failed to get image URL:', error);
    
    if (error.statusCode) {
      throw error; // Re-throw HTTP errors
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to retrieve profile image',
    });
  }
});
