import type { RequestEvent, RequestHandler } from '@builder.io/qwik-city';

const proxy = async ({ send, url, pathname, request }: RequestEvent) => {
  const targetUrl = new URL(`http://localhost:8081${pathname}`, url);
  const headers = new Headers(request.headers);

  const fetchOptions: RequestInit = {
    method: request.method,
    headers,
    redirect: 'manual',
  };

  if (request.method !== 'GET' && request.method !== 'HEAD') {
    fetchOptions.body = request.body;
    (fetchOptions as any).duplex = 'half';
  }

  const res = await fetch(targetUrl, fetchOptions);

  send(
    new Response(res.body, {
      status: res.status,
      statusText: res.statusText,
      headers: res.headers,
    })
  );
};

export const onGet: RequestHandler = proxy;
export const onPost: RequestHandler = proxy;
export const onDelete: RequestHandler = proxy;