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

const intlMiddleware = createMiddleware(routing);

function adminBasicAuth(req: NextRequest) {
  const user = process.env.ADMIN_USER;
  const pass = process.env.ADMIN_PASSWORD;

  if (!user || !pass) return NextResponse.next();

  const authHeader = req.headers.get("authorization");
  if (!authHeader?.startsWith("Basic ")) {
    return new NextResponse("Authentication required", {
      status: 401,
      headers: { "WWW-Authenticate": 'Basic realm="Admin"' },
    });
  }

  const base64 = authHeader.slice("Basic ".length);
  const decoded = Buffer.from(base64, "base64").toString("utf8");
  const [u, p] = decoded.split(":");

  if (u !== user || p !== pass) {
    return new NextResponse("Invalid credentials", {
      status: 401,
      headers: { "WWW-Authenticate": 'Basic realm="Admin"' },
    });
  }

  return NextResponse.next();
}

/** Strip `/:locale` when the first segment is a configured locale (for admin/api checks). */
function stripLocalePrefix(pathname: string): { locale: string | null; rest: string } {
  for (const loc of routing.locales) {
    if (pathname === `/${loc}`) return { locale: loc, rest: "/" };
    if (pathname.startsWith(`/${loc}/`)) {
      const rest = pathname.slice(`/${loc}`.length) || "/";
      return { locale: loc, rest };
    }
  }
  return { locale: null, rest: pathname };
}

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

  if (pathname.startsWith("/api")) {
    return NextResponse.next();
  }

  const { locale, rest } = stripLocalePrefix(pathname);

  // Admin lives outside `[locale]` — never run i18n rewrites on it. Also fix `/:locale/admin` → `/admin`.
  if (rest === "/admin" || rest.startsWith("/admin/")) {
    if (locale != null) {
      const url = req.nextUrl.clone();
      url.pathname = rest;
      return NextResponse.redirect(url);
    }
    return adminBasicAuth(req);
  }

  return intlMiddleware(req);
}

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