import { beforeEach, describe, expect, it, vi } from "vitest";

vi.mock("next/cache", async () => ({ revalidatePath: (await import("@/tests/helpers/next-mocks")).revalidatePath }));
vi.mock("next/navigation", async () => ({ redirect: (await import("@/tests/helpers/next-mocks")).redirect }));
vi.mock("next/dist/client/components/redirect-error", async () => ({
  isRedirectError: (await import("@/tests/helpers/next-mocks")).isRedirectError,
}));
vi.mock("@/lib/admin-auth", async () => {
  const m = await import("@/tests/helpers/next-mocks");
  return { isAdminAuthenticated: m.isAdminAuthenticated, clearAdminSessionCookie: m.clearAdminSessionCookie };
});

import { updateMaintenanceModeAction } from "@/app/_admin/maintenance/actions";
import { getMaintenanceMode } from "@/lib/app-config";
import { adminAuth, captureRedirect, formDataFrom, resetNextMocks } from "@/tests/helpers/next-mocks";

beforeEach(() => {
  resetNextMocks();
});

describe("updateMaintenanceModeAction", () => {
  it("enables maintenance mode and redirects with a success flash", async () => {
    const url = await captureRedirect(() => updateMaintenanceModeAction(formDataFrom({ enabled: "true" })));
    expect(url).toContain("success=");
    expect(await getMaintenanceMode()).toBe(true);
  });

  it("disables maintenance mode", async () => {
    await captureRedirect(() => updateMaintenanceModeAction(formDataFrom({ enabled: "true" })));
    await captureRedirect(() => updateMaintenanceModeAction(formDataFrom({ enabled: "false" })));
    expect(await getMaintenanceMode()).toBe(false);
  });

  it("redirects unauthenticated callers to the admin root", async () => {
    adminAuth.authenticated = false;
    const url = await captureRedirect(() => updateMaintenanceModeAction(formDataFrom({ enabled: "true" })));
    expect(url).toBe("/");
    // state unchanged
    expect(await getMaintenanceMode()).toBe(false);
  });
});
