// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

// the following code is taken from : https://nextjs.org/docs/advanced-features/middleware#setting-headers
export function middleware(request: NextRequest) {
  const protocol = request.headers.get("x-forwarded-proto") || "http"; // Default to 'http' if not provided
  const host = request.headers.get("x-forwarded-host") || request.nextUrl.hostname;
  const path = request.nextUrl.pathname + request.nextUrl.search;
  const siteName = "Dynamic Realty";
  const metaDesc =
    "Dynamic Realty is a full-service veteran-owned real estate company based in Centerville, GA, established in 2004.";

  // Construct the full URL
  const mainUrl = `${protocol}://${host}`;
  const fullUrl = `${mainUrl}${path}`;
  request.headers.set("x-main-url", mainUrl);
  request.headers.set("x-full-url", fullUrl);
  request.headers.set("x-site-name", siteName);
  request.headers.set("x-meta-desc", metaDesc);

  // redirect for /blog/<slug>/ path
  const blogPathRegex = /^\/blog\/([^\/]+)(\/[^\/]*)*\/?$/;
  if (blogPathRegex.test(path) && !path.includes("/blog/?")) {
    const newBlogPath = path.replace(/^\/blog/, "") || "/";
    return NextResponse.redirect(`${mainUrl}${newBlogPath}`, 301);
  }
  // redirect for /about/<slug>/ path
  const aboutPathRegex = /^\/about\/([^\/]+)(\/[^\/]*)*\/?$/;
  if (aboutPathRegex.test(path)) {
    const newAboutPath = path.replace(/^\/about/, "") || "/";
    return NextResponse.redirect(`${mainUrl}${newAboutPath}`, 301);
  }

  return NextResponse.next({
    request: {
      // New request headers
      headers: request.headers,
    },
  });
}

// the following code has been copied from https://nextjs.org/docs/advanced-features/middleware#matcher
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    "/((?!api|_next/static|_next/image|assets|sw.js|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
};
