import { gatewayUrl, forwardAuth } from '~/lib/server/gateway';

export async function GET({ request }: { request: Request }) {
  try {
    const upstreamUrl = gatewayUrl('/api/me/notifications/unread-count');
    const upstreamInit: RequestInit = {
      method: 'GET',
      headers: {
        ...forwardAuth(request),
        Accept: 'application/json',
      },
      credentials: 'include',
    };

    const response = await fetch(upstreamUrl, upstreamInit);
    const responseHeaders = new Headers();
    response.headers.forEach((value, key) => {
      if (!['server', 'transfer-encoding', 'connection'].includes(key.toLowerCase())) {
        responseHeaders.set(key, value);
      }
    });
    responseHeaders.set('Content-Type', 'application/json');

    const responseBody = await response.text();
    return new Response(responseBody, {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
    });
  } catch (error: any) {
    return new Response(
      JSON.stringify({ success: false, unread_count: 0 }),
      { status: 200, headers: { 'Content-Type': 'application/json' } },
    );
  }
}
