export const UPSTREAM_API =
  process.env.UPSTREAM_API_URL ?? "https://api.modstagram.ir";

type ProxyOptions = {
  stripAuth?: boolean;
};

const PUBLIC_AUTH_PATTERNS = [
  /^\/login\/?$/,
  /^\/login\/verify$/,
  /^\/login\/login_username$/,
  /^\/login\/forgot_password$/,
  /^\/register\/?$/,
  /^\/register\/verify$/,
  /^\/auth\/google$/,
];

export function isPublicAuthPath(pathSegments: string[]): boolean {
  const path = `/${pathSegments.join("/")}`;
  return PUBLIC_AUTH_PATTERNS.some((pattern) => pattern.test(path));
}

export async function proxyToUpstream(
  req: Request,
  upstreamPath: string,
  options?: ProxyOptions
): Promise<Response> {
  const url = new URL(upstreamPath, UPSTREAM_API);
  const incoming = new URL(req.url);
  url.search = incoming.search;

  const headers = new Headers();
  const contentType = req.headers.get("content-type");
  if (contentType) headers.set("content-type", contentType);

  if (!options?.stripAuth) {
    const auth = req.headers.get("authorization");
    if (auth) headers.set("authorization", auth);
  }

  const method = req.method;
  const body =
    method !== "GET" && method !== "HEAD" ? await req.arrayBuffer() : undefined;

  const upstream = await fetch(url.toString(), {
    method,
    headers,
    body,
    cache: "no-store",
  });

  const responseHeaders = new Headers();
  const upstreamType = upstream.headers.get("content-type");
  if (upstreamType) responseHeaders.set("content-type", upstreamType);

  return new Response(upstream.body, {
    status: upstream.status,
    headers: responseHeaders,
  });
}
