"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

import { routing } from "@/i18n/routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getLocalizedPath } from "@/lib/locale";
import { setMaintenanceMode } from "@/lib/app-config";

function ensureAdmin() {
  if (!isAdminAuthenticated()) {
    clearAdminSessionCookie();
    redirect("/root");
  }
}

export async function updateMaintenanceModeAction(formData: FormData) {
  ensureAdmin();

  const nextValue = formData.get("enabled") === "true";
  const redirectPath = String(formData.get("redirectPath") ?? "/root");
  const redirectUrl = new URL(redirectPath, "http://localhost");
  redirectUrl.searchParams.set(
    "success",
    nextValue ? "Wartungsmodus aktiviert." : "Wartungsmodus deaktiviert.",
  );

  await setMaintenanceMode(nextValue);
  revalidatePath("/", "layout");
  revalidatePath("/coming-soon");
  revalidatePath("/root");
  revalidatePath("/root/maintenance");
  revalidatePath(redirectPath);

  for (const appLocale of routing.locales) {
    revalidatePath(getLocalizedPath(appLocale), "layout");
    revalidatePath(getLocalizedPath(appLocale, "/coming-soon"));
  }

  redirect(`${redirectUrl.pathname}${redirectUrl.search}`);
}
