export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig(event);
  const backendUrl = new URL(config.backendGraphqlUrl);
  const connectionId = getRouterParam(event, 'connectionId');

  if (!connectionId) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Connection id is required.',
    });
  }

  const response = await fetch(`${backendUrl.origin}/messenger/avatar/${encodeURIComponent(connectionId)}`, {
    headers: {
      ...(getHeader(event, 'cookie') ? { cookie: getHeader(event, 'cookie') as string } : {}),
      ...(getHeader(event, 'authorization') ? { authorization: getHeader(event, 'authorization') as string } : {}),
    },
  });

  if (!response.ok || !response.body) {
    throw createError({
      statusCode: response.status,
      statusMessage: 'Messenger avatar is not available.',
    });
  }

  setResponseStatus(event, response.status);
  setHeader(event, 'content-type', response.headers.get('content-type') || 'image/jpeg');
  setHeader(event, 'cache-control', response.headers.get('cache-control') || 'private, max-age=300');

  return Buffer.from(await response.arrayBuffer());
});
