import createMiddleware from "next-intl/middleware";
import { type NextRequest, NextResponse } from "next/server";
import { routing } from "./i18n/routing";

const intlMiddleware = createMiddleware(routing);

const protectedPaths = ["/dashboard", "/security", "/servers"];

function getPathWithoutLocale(pathname: string): string {
  if (pathname === "/en" || pathname.startsWith("/en/")) {
    return pathname.slice(3) || "/";
  }

  return pathname;
}

function buildLocalizedPath(path: string, pathname: string): string {
  if (pathname === "/en" || pathname.startsWith("/en/")) {
    return `/en${path}`;
  }

  return path;
}

export default function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const pathWithoutLocale = getPathWithoutLocale(pathname);

  const isProtected = protectedPaths.some(
    (protectedPath) =>
      pathWithoutLocale === protectedPath ||
      pathWithoutLocale.startsWith(`${protectedPath}/`),
  );

  if (isProtected) {
    const session = request.cookies.get("hgc_session");

    if (!session?.value) {
      const loginUrl = request.nextUrl.clone();
      loginUrl.pathname = buildLocalizedPath("/login", pathname);
      loginUrl.searchParams.set("redirect", pathname);
      return NextResponse.redirect(loginUrl);
    }
  }

  return intlMiddleware(request);
}

export const config = {
  matcher: ["/", "/(de|en)/:path*", "/((?!_next|_vercel|.*\\..*).*)"],
};
