"use server";

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

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

async function ensureAdmin() {
  if (!(await isAdminAuthenticated())) {
    await clearAdminSessionCookie();
    redirect(getAdminAppPath("/"));
  }
}

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

  const nextValue = formData.get("enabled") === "true";
  const redirectPath = String(formData.get("redirectPath") ?? getAdminAppPath("/"));
  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(toInternalAdminPath("/"));
  revalidatePath(toInternalAdminPath("/maintenance"));
  revalidatePath(toInternalAdminPath(redirectUrl.pathname));

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

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