import { defineMiddleware } from "astro:middleware";
import { getSession, isApiAuthorized } from "./pages/api/lib/auth";

const LOCALES = new Set(["es", "en", "fr", "he", "uk", "pt", "ru", "rw", "kr"]);

export const onRequest = defineMiddleware(async (context, next) => {
  const { url, request, redirect } = context;
  const pathname = url.pathname;

  if (pathname === "/admin" || pathname === "/admin/") {
    return redirect("/es/admin", 302);
  }

  if (pathname.startsWith("/api/admin/")) {
    const isAuthEndpoint =
      pathname.endsWith("/auth/login") || pathname.endsWith("/auth/logout");

    if (request.method !== "GET" && !isAuthEndpoint) {
      return new Response(
        JSON.stringify({ success: false, message: "Method not allowed" }),
        { status: 405, headers: { "Content-Type": "application/json" } }
      );
    }

    if (!isAuthEndpoint && !(await isApiAuthorized(request))) {
      return new Response(
        JSON.stringify({ success: false, message: "Unauthorized" }),
        { status: 401, headers: { "Content-Type": "application/json" } }
      );
    }

    return next();
  }

  const segments = pathname.split("/").filter(Boolean);
  if (segments.length >= 2 && segments[1] === "admin") {
    const locale = LOCALES.has(segments[0]) ? segments[0] : "es";
    const isLogin = segments[2] === "login";
    const session = await getSession(request);

    if (!isLogin && !session) {
      return redirect(`/${locale}/admin/login`, 302);
    }

    if (isLogin && session) {
      return redirect(`/${locale}/admin`, 302);
    }
  }

  return next();
});
