import assert from "node:assert/strict";
import { describe, test } from "node:test";
import type { FormikProps } from "formik";
import moment from "moment";
import { canPublish, getPublishPermissions, publishIntentFromNav } from "@/lib/publishPermissions";
import { routeAccess } from "@/components/shared/routeAccess";
import { authoringAccessError } from "@/features/shared/authoringAccess";
import { buildSubmitClickHandler } from "@/features/opportunities/components/useLearnServeFormSubmitClick";
import { buildLearnServeInitialValues } from "@/features/opportunities/components/learnServeInitialValues";
import type { LearnServeFormValues } from "@/features/opportunities/components/learnServeFormTypes";
import type { PendingSubmission } from "@/features/opportunities/components/useLearnServeSubmit";
import type { User } from "@/store/authStore";
import { announcementImages } from "@/features/shared/uploadedImage";
import { installDom, renderHook } from "./reactHarness";
import { NAV_STATE_KEYS, setNavState, takeNavState } from "@/lib/navigationState";
import { usePublishFormIntent } from "@/components/shared/usePublishFormIntent";

const organization = {
  id: 8, user_type: "organization", is_verified: true, is_banned: false,
  is_publishing_paused: true, organizer_type_display: { value_en: "Charity" },
} as User;

describe("PDF page 33: pause new publishing, preserve existing work", () => {
  test("a paused approved organization can edit its existing content", () => {
    const permissions = getPublishPermissions(organization, "edit");
    for (const key of ["volunteer", "development", "internship", "events"] as const) assert.equal(permissions[key], true);
    assert.equal(permissions.developmentPaid, true);
    assert.equal(routeAccess({ user: organization, publish: "events", publishIntent: "edit" }).allow, true);
  });
  test("create and repost remain blocked during the pause", () => {
    for (const intent of ["create", "repost"] as const) {
      assert.equal(canPublish(organization, ["development", "internship"], intent), false);
      assert.equal(routeAccess({ user: organization, publish: "volunteer", publishIntent: intent }).allow, false);
    }
    assert.equal(canPublish(organization, "events"), false);
  });
  test("edit permission preserves the team's publishing matrix", () => {
    const team = { ...organization, organizer_type_display: { value_en: "Volunteer Team" } };
    const permissions = getPublishPermissions(team, "edit");
    assert.equal(permissions.volunteer, true);
    assert.equal(permissions.development, true);
    for (const key of ["events", "internship", "developmentPaid"] as const) assert.equal(permissions[key], false);
  });
  test("the edit intent cannot bypass approval, ban or unknown publisher kind", () => {
    for (const user of [{ ...organization, is_verified: false }, { ...organization, is_banned: true }, { ...organization, organizer_type_display: null }]) {
      assert.equal(canPublish(user, "volunteer", "edit"), false);
    }
    assert.equal(routeAccess({ user: null, publish: "events", publishIntent: "edit" }).redirectTo, "/login");
  });
  test("only a valid source ID is classified as an edit/repost", () => {
    assert.equal(publishIntentFromNav({ id: "42" }), "edit");
    assert.equal(publishIntentFromNav({ id: 42, isRepublish: false }), "edit");
    assert.equal(publishIntentFromNav({ id: "42", isRepublish: true }), "repost");
    for (const value of [null, {}, { id: "" }, { id: 0 }, { id: -1 }, { id: "Infinity" }, { id: [] }, { id: 1.5 }, { id: 42, isRepublish: "false" }]) assert.equal(publishIntentFromNav(value), "create");
  });
  test("consuming navigation state cannot turn a paused edit into a create", () => {
    installDom();
    setNavState(NAV_STATE_KEYS.volunteerForm, { id: "42", isRepublish: false });
    const edit = renderHook(() => usePublishFormIntent("create", NAV_STATE_KEYS.volunteerForm), { strict: true });
    edit.mount();
    assert.equal(edit.last(), "edit");
    assert.deepEqual(takeNavState(NAV_STATE_KEYS.volunteerForm), { id: "42", isRepublish: false });
    edit.rerender();
    assert.equal(edit.last(), "edit");
    edit.unmount();
    const nextVisit = renderHook(() => usePublishFormIntent("create", NAV_STATE_KEYS.volunteerForm));
    nextVisit.mount();
    assert.equal(nextVisit.last(), "create");
    nextVisit.unmount();
  });
});

describe("PDF pages 13/18/37: edit and repost guards", () => {
  const source = { id: 42, created_by: { id: 8 }, start_at: "2026-11-04T16:00:00+03:00", end_at: "2026-11-04T18:00:00+03:00" };
  const target = { id: "42", source, userId: 8 };
  test("a fresh create has no source-record requirement", () => {
    assert.equal(authoringAccessError({ userId: 8 }), null);
  });
  test("missing/failed source loads cannot become a blank editable record", () => {
    assert.equal(authoringAccessError({ id: "42", userId: 8 }), "COMMON.PUBLISH_SOURCE_UNAVAILABLE");
  });
  test("another publisher, missing session and mismatched record are refused", () => {
    const now = moment.parseZone("2026-11-02T12:00:00+03:00");
    for (const input of [{ ...target, userId: 9 }, { ...target, userId: null }, { ...target, id: "43" }]) assert.equal(authoringAccessError(input, now), "COMMON.PUBLISH_SOURCE_UNAVAILABLE");
  });
  test("the same pending confirmation expires at the actual 24-hour boundary", () => {
    assert.equal(authoringAccessError(target, moment.parseZone("2026-11-03T16:00:00+03:00")), null);
    assert.equal(authoringAccessError(target, moment.parseZone("2026-11-03T16:00:01+03:00")), "COMMON.EDIT_WINDOW_CLOSED");
    assert.equal(authoringAccessError(target, moment.parseZone("2026-11-04T17:00:00+03:00")), "COMMON.EDIT_WINDOW_CLOSED");
  });
  test("reposting opens at actual start and remains possible after completion", () => {
    const repost = { ...target, isRepublish: true };
    assert.equal(authoringAccessError(repost, moment.parseZone("2026-11-04T15:59:59+03:00")), "COMMON.PUBLISH_SOURCE_UNAVAILABLE");
    assert.equal(authoringAccessError(repost, moment.parseZone("2026-11-04T16:00:00+03:00")), null);
    assert.equal(authoringAccessError(repost, moment.parseZone("2026-11-07T20:00:00+03:00")), null);
  });
  test("server ownership flags/relationships work without a legacy creator ID", () => {
    const now = moment.parseZone("2026-11-02T12:00:00+03:00");
    for (const ownership of [{ is_creator: true }, { relationship_tags: ["organizer"] }]) assert.equal(authoringAccessError({ ...target, source: { ...source, created_by: null, ...ownership } }, now), null);
  });
});

describe("PDF page 37: confirmed development edits retain inline errors", () => {
  const values = buildLearnServeInitialValues({ selectedLanguage: "ar", hasDistinctEnglishTitle: false, hasDistinctEnglishDescription: false, tagOptions: [] });
  function setup({ id, isRepublish, invalid = false }: { id?: string; isRepublish?: boolean; invalid?: boolean }) {
    let pending: PendingSubmission | null = null;
    let confirmed = false;
    let submitted = 0;
    const fieldErrors: Record<string, string> = {};
    const bag = {
      values, setTouched: async () => {}, validateForm: async () => invalid ? { title_ar: "required" } : {},
      submitForm: async () => { submitted++; }, setFieldError: (key: string, value: string) => { fieldErrors[key] = value; },
    } as unknown as FormikProps<LearnServeFormValues>;
    const click = buildSubmitClickHandler({ bag, id, isRepublish, errorFieldSelectors: {}, setPendingFormData: next => { pending = next; }, setShowUpdateConfirmModal: open => { confirmed = open; } });
    return { click, bag, fieldErrors, pending: () => pending, confirmed: () => confirmed, submitted: () => submitted };
  }
  test("the pending edit holds the real Formik field setter", async () => {
    const form = setup({ id: "42" });
    await form.click();
    assert.equal(form.confirmed(), true);
    assert.equal(form.submitted(), 0);
    const pending = form.pending();
    assert.ok(pending);
    assert.equal(pending.helpers.setFieldError, form.bag.setFieldError);
    pending.helpers.setFieldError("price", "Rejected price");
    assert.equal(form.fieldErrors.price, "Rejected price");
    assert.equal(pending.values, values);
  });
  test("create and repost use the normal Formik submit rather than an edit confirmation", async () => {
    for (const input of [{}, { id: "42", isRepublish: true }]) {
      const form = setup(input);
      await form.click();
      assert.equal(form.confirmed(), false);
      assert.equal(form.pending(), null);
      assert.equal(form.submitted(), 1);
    }
  });
  test("invalid fields stop both submission and confirmation", async () => {
    installDom();
    const form = setup({ id: "42", invalid: true });
    await form.click();
    assert.equal(form.pending(), null);
    assert.equal(form.confirmed(), false);
    assert.equal(form.submitted(), 0);
  });
});

test("PDF page 13: a repost may copy the announcement, never the old completion gallery", () => {
  const media = [{ id: 1, image: "/poster.png", is_after_completed: false }, { id: 2, image: "/old-attendance.jpg", is_after_completed: true }];
  assert.deepEqual(announcementImages(media), [{ id: 1, image: "/poster.png" }]);
  assert.equal(media.length, 2);
});
