"use server";

import { NextResponse } from "next/server";
import fs from "fs";
import { permanentRedirect, redirect } from "next/navigation";
// the following code is taken from : https://nextjs.org/docs/advanced-features/middleware#setting-headers
export async function middleware(request) {
  let dirs = [
    "",
    "blogs",
    "commercial-litigation",
    "criminal-lawsuits",
    "family-lawsuits",
    "financial-claims",
    "lawyers",
    "property-claims",
  ];
  const firstPathname = request.nextUrl.pathname.split("/")[1];
  const isLocalPath = !!dirs.includes(firstPathname);

  console.log("ssssss", firstPathname);

  if (isLocalPath) {
    console.log("middleware", request.nextUrl.pathname);
    return NextResponse.next();
  } else {
    try {
      const data = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/blog/newlink?slug=${firstPathname}`
      );
      const newLink = await data.text();
      console.log("hi", newLink);
      // return NextResponse.redirect(new URL(data), 308);
      return NextResponse.redirect(new URL(newLink), 308);
    } catch (error) {
      return NextResponse.next();
    }

    // return NextResponse.redirect(new URL(`${request.nextUrl.origin}/`), 308);
  }
}

// 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 (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon|fonts|favicon.ico).*)",
  ],
};
