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 { saveMarqueeSettingsAction } from "@/app/_admin/marquee/actions";
import { getMarqueeSettings } from "@/lib/app-config";
import { adminAuth, captureRedirect, formDataFrom, resetNextMocks } from "@/tests/helpers/next-mocks";

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

const validRows = {
  "row1-de": "A\nB",
  "row2-de": "C\nD",
  "row3-de": "E\nF",
  "row4-de": "G\nH",
};

describe("saveMarqueeSettingsAction", () => {
  it("saves german rows and mirrors them across locales", async () => {
    const url = await captureRedirect(() => saveMarqueeSettingsAction(formDataFrom(validRows)));
    expect(url).toContain("success=");

    const settings = await getMarqueeSettings();
    expect(settings.locales.de.row1).toBe("A\nB");
    expect(settings.locales.en.row1).toBe("A\nB");
    expect(settings.locales.ar.row4).toBe("G\nH");
  });

  it("redirects with an error when a required row is empty", async () => {
    const url = await captureRedirect(() =>
      saveMarqueeSettingsAction(formDataFrom({ ...validRows, "row2-de": "   " })),
    );
    expect(url).toContain("error=");
  });

  it("redirects unauthenticated callers to the admin root", async () => {
    adminAuth.authenticated = false;
    const url = await captureRedirect(() => saveMarqueeSettingsAction(formDataFrom(validRows)));
    expect(url).toBe("/");
  });
});
