import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { defaultLocale, isLocale, resolvePublicPath, toInternalPath, toPublicFromInternal, switchLocale } from "@/i18n/routes";
import { readCookieFromHeader } from "@/lib/auth/cookie";
import { verifySession } from "@/lib/auth/session";

const PUBLIC_FILE = /\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml|json|css|js|map)$/;

function isAdminLoginPath(pathname: string): boolean {
  return pathname === "/admin/login" || pathname.startsWith("/admin/login/");
}

function isAdminPath(pathname: string): boolean {
  return pathname === "/admin" || pathname.startsWith("/admin/");
}

function isAdminApiPath(pathname: string): boolean {
  return pathname === "/api/admin/login" || pathname.startsWith("/api/admin/");
}

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const headers = new Headers(request.headers);

  // Locale-Auflösung
  const segment = pathname.split("/")[1] ?? "";
  const locale = isLocale(segment) ? segment : defaultLocale;
  headers.set("x-locale", locale);

  // Admin-Auth
  const cookieHeader = request.headers.get("cookie");
  const sessionToken = readCookieFromHeader(cookieHeader);
  const authenticated = verifySession(sessionToken);

  if (isAdminApiPath(pathname) && !pathname.startsWith("/api/admin/login")) {
    if (!authenticated) {
      return NextResponse.json({ error: "unauthorized" }, { status: 401 });
    }
  }
  if (isAdminPath(pathname) && !isAdminLoginPath(pathname)) {
    if (!authenticated) {
      const url = request.nextUrl.clone();
      url.pathname = "/admin/login";
      url.searchParams.set("next", pathname);
      return NextResponse.redirect(url);
    }
  }

  // /de/... → public
  if (pathname === "/de" || pathname.startsWith("/de/")) {
    const publicPath = toPublicFromInternal(pathname);
    if (publicPath && publicPath !== pathname) {
      const url = request.nextUrl.clone();
      url.pathname = publicPath;
      return NextResponse.redirect(url);
    }
  }

  // public → /<locale>/...
  const internal = toInternalPath(pathname);
  if (internal && internal !== pathname) {
    const url = request.nextUrl.clone();
    url.pathname = internal;
    return NextResponse.rewrite(url, { request: { headers } });
  }

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

export const config = {
  matcher: [
    // Alles außer Next.js-interne Pfade, statische Files, OG/Robots/Sitemap,
    // sowie /admin/* und /api/admin/* (Auth passiert vor Locale-Rewrite).
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml)$).*)",
  ],
};
