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

const locales = ["en", "de"];
const defaultLocale = "de";

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

    // Check if there is any supported locale in the pathname
    const pathnameHasLocale = locales.some(
        (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
    );

    if (pathnameHasLocale) return;

    if (pathname.startsWith("/api") || pathname.includes("sw.js") || pathname.includes("workbox")) return NextResponse.next();

    // Redirect if there is no locale
    const locale = defaultLocale; // For simplicity, we default to 'de' as requested
    request.nextUrl.pathname = `/${locale}${pathname}`;

    // Keep searching if the URL changes
    return NextResponse.redirect(request.nextUrl);
}

export const config = {
    matcher: [
        // Skip all internal paths (_next)
        "/((?!_next|api|public|manifest|icon|file|globe|next|vercel|window|push-sw.js|sw.js|workbox).*)",
    ],
};
