import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: [
    /*
     * Match all paths except for:
     * 1. /api routes
     * 2. /_next (Next.js internals)
     * 3. /fonts (inside /public)
     * 4. /examples (inside /public)
     * 5. all root files inside /public (e.g. /favicon.ico)
     */
    "/((?!api|_next|fonts|login|signup|examples|[\\w-]+\\.\\w+).*)",
  ],
};

export default function middleware(req: NextRequest) {
  const url = req.nextUrl;

  // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
  const hostname = req.headers.get("host") || "learnhouse.app";

  // Only for demo purposes - remove this if you want to use your root domain as the landing page
  if (hostname === "vercel.pub" || hostname === "platforms.vercel.app") {
    return NextResponse.redirect("https://demo.vercel.pub");
  }

  /*  You have to replace ".vercel.pub" with your own domain if you deploy this example under your domain.
      You can also use wildcard subdomains on .vercel.app links that are associated with your Vercel team slug
      in this case, our team slug is "platformize", thus *.platformize.vercel.app works. Do note that you'll
      still need to add "*.platformize.vercel.app" as a wildcard domain on your Vercel dashboard. */
  let currentHost =
    process.env.NODE_ENV === "production" && process.env.VERCEL === "1"
      ? hostname.replace(`.vercel.pub`, "").replace(`.platformize.vercel.app`, "")
      : hostname.replace(`.localhost:3000`, "");
  
  // if url starts with "/organizations" rewrite to path 
  if (url.pathname.startsWith("/organizations")) {
    url.pathname = url.pathname.replace("/organizations", `/organizations/${currentHost}`);
    // remove localhost:3000 from url
    url.pathname = url.pathname.replace(`localhost:3000`, "");
    console.log(url);
    
    return NextResponse.rewrite(url);
  }

  else if (url.pathname.startsWith("/org")) {
    url.pathname = url.pathname.replace("/organizations", `/_orgs/${currentHost}`);
    // remove localhost:3000 from url
    
    url.pathname = `/_orgs/${currentHost}${url.pathname}`;
    url.pathname = url.pathname.replace(`localhost:3000/org/`, "");
    console.log(url);
    
    return NextResponse.rewrite(url);
  }

  // rewrite everything else to `/_sites/[site] dynamic route
  url.pathname = `/_orgs/${currentHost}${url.pathname}`;
  console.log(url);
  
  return NextResponse.rewrite(url, { headers: { "olgslug": currentHost } });
}
