import { NextResponse, type NextRequest } from "next/server";
import { env } from "~/env.mjs";

export const apisMiddleware = async (req: NextRequest) => {
  const path = req.nextUrl.pathname;

  const rewrite_paths = ["/go-api/images/", "/go-api/storage/"];
  if (!rewrite_paths.some((p) => path.startsWith(p))) {
    return;
  }

  if (
    path.startsWith("/go-api/images/") ||
    path.startsWith("/go-api/storage/")
  ) {
    // Handle image and storage requests
    const newPath = path
      .replace("/go-api/images/", "/images/")
      .replace("/go-api/storage/", "/storage/");

    const url = new URL(`${env.BACKENDSERVER_URL}${newPath}`, req.url);
    const res = NextResponse.rewrite(url);
    res.headers.set("Access-Control-Allow-Origin", env.NEXT_PUBLIC_BASE_URL);

    res.headers.set(
      "Access-Control-Allow-Methods",
      "GET, POST, PUT, DELETE, OPTIONS",
    );
    res.headers.set(
      "Access-Control-Allow-Headers",
      "Content-Type, Authorization",
    );
    return res;

    // Fetch the content from the backend and serve it through the middleware
    const response = await fetch(url.toString(), {
      headers: req.headers,
    });

    return new NextResponse(response.body, {
      headers: response.headers,
      status: response.status,
    });
  }
};
