/**
 * Regression tests for the development-opportunity request payload.
 *
 * This is the wire format the backend validates against, so a silent change
 * here is a silent change to what gets saved. The rules covered are the ones
 * that are conditional — a field that is only sometimes sent, or sent with a
 * different value depending on the account and the type — because those are
 * the ones a refactor can drop without anything failing to compile.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { buildLearnServePayload } from "@/features/opportunities/components/buildLearnServePayload";
import type { LearnServeFormValues } from "@/features/opportunities/components/learnServeFormTypes";
import type { PublishPermissions } from "@/lib/publishPermissions";

const permissions = (over: Partial<PublishPermissions> = {}): PublishPermissions =>
  ({
    volunteer: true,
    development: true,
    internship: true,
    developmentPaid: true,
    developmentTypes: null,
    ...over,
  }) as PublishPermissions;

const values = (over: Partial<LearnServeFormValues> = {}): LearnServeFormValues =>
  ({
    title_ar: "عنوان",
    title_en: "English title",
    description_ar: "<p>وصف</p>",
    description_en: "",
    dueDate: "2027-01-01",
    startDate: "2027-02-01",
    endDate: "2027-02-05",
    startTime: "09:00",
    endTime: "12:00",
    age: [18, 30] as [number | null, number | null],
    participantsNeeded: "20",
    learningType: "course-id",
    learnServeFormat: "inperson-id",
    certificateType: "",
    gender: "gender-id",
    location: "Kuwait",
    location_url: "",
    latitude: "",
    longitude: "",
    meetingLink: "",
    whatsappLink: "",
    is_paid: "false",
    price: "",
    opportunity_images: [],
    license_image: "",
    license_image_removed: false,
    _interests: [],
    sponsors: [{ sponsorId: "", position: 1 }],
    opportunity_nationality: "all",
    primary_language: "ar",
    ...over,
  }) as LearnServeFormValues;

const args = {
  isUpdate: false,
  existingImageIds: [] as number[],
  publishPermissions: permissions(),
  internshipTypeId: "internship-id",
  courseTypeId: "course-id",
  onlineFormatId: "online-id",
};

/** FormData entries as a plain list, so repeated keys stay visible. */
const entries = (fd: FormData) =>
  [...fd.entries()].map(([k, v]) => [k, typeof v === "string" ? v : "<file>"]);
const get = (fd: FormData, key: string) => fd.get(key);

describe("buildLearnServePayload", () => {
  test("falls the English title back to the Arabic one", () => {
    // The column is non-null server-side; an opportunity written only in
    // Arabic still has to satisfy it.
    const { formData } = buildLearnServePayload({ ...args, values: values() });
    assert.equal(get(formData, "title_ar"), "عنوان");
    assert.equal(get(formData, "title_en"), "English title");
  });

  test("sends booleans as 1/0, not 'true'/'false'", () => {
    // The API's `boolean` rule rejects the literal strings.
    const { formData } = buildLearnServePayload({
      ...args,
      values: values({ is_paid: "true", price: "5" }),
    });
    assert.ok(["1", "0"].includes(String(get(formData, "is_paid"))));
  });

  test("never sends paid for an internship, even if the form still says paid", () => {
    // Internships are free by rule. A stale "true" left in the form from before
    // the type was switched must not reach the server.
    const { formData } = buildLearnServePayload({
      ...args,
      values: values({ learningType: "internship-id", is_paid: "true", price: "50" }),
    });
    assert.equal(get(formData, "is_paid"), "0");
    assert.equal(get(formData, "price"), null, "price is only sent when paid");
  });

  test("never sends paid when the account may not charge", () => {
    const { formData } = buildLearnServePayload({
      ...args,
      publishPermissions: permissions({ developmentPaid: false }),
      values: values({ is_paid: "true", price: "50" }),
    });
    assert.equal(get(formData, "is_paid"), "0");
  });

  test("sends price only on the paid branch", () => {
    const paid = buildLearnServePayload({
      ...args,
      values: values({ is_paid: "true", price: "50" }),
    }).formData;
    assert.equal(get(paid, "price"), "50");
  });

  test("sends a meeting link for online and an address for in person", () => {
    const online = buildLearnServePayload({
      ...args,
      values: values({
        learnServeFormat: "online-id",
        meetingLink: "https://example.com/room",
      }),
    }).formData;
    assert.equal(get(online, "link"), "https://example.com/room");
    assert.equal(get(online, "map_desc"), null);

    const inPerson = buildLearnServePayload({
      ...args,
      values: values({ learnServeFormat: "inperson-id", location: "Kuwait" }),
    }).formData;
    assert.equal(get(inPerson, "map_desc"), "Kuwait");
    assert.equal(get(inPerson, "link"), null);
  });

  test("sends the WhatsApp contact for both formats", () => {
    // BE-65 — the contact belongs to the opportunity, not to its format.
    for (const format of ["online-id", "inperson-id"]) {
      const { formData } = buildLearnServePayload({
        ...args,
        values: values({ learnServeFormat: format, whatsappLink: "https://wa.me/1" }),
      });
      assert.equal(get(formData, "whatsapp_link"), "https://wa.me/1", format);
    }
  });

  test("a repost explicitly copies its selected announcement media", () => {
    // RepublishMedia::apply() copies exactly this selected announcement keep-set.
    const { formData } = buildLearnServePayload({
      ...args,
      isRepublish: true,
      id: 42,
      existingImageIds: [1, 2, 3],
      values: values(),
    });
    assert.equal(get(formData, "opportunity_id"), "42");
    assert.equal(get(formData, "existing_image_ids"), null);
    assert.deepEqual(formData.getAll("existing_image_ids[]"), ["1", "2", "3"]);
  });

  test("an edit keeps the images the organizer did not remove", () => {
    const { formData } = buildLearnServePayload({
      ...args,
      isUpdate: true,
      id: 42,
      existingImageIds: [1, 2],
      values: values(),
    });
    assert.deepEqual(
      entries(formData)
        .filter(([k]) => k === "existing_image_ids[]")
        .map(([, v]) => v),
      ["1", "2"]
    );
    assert.equal(get(formData, "existing_image_ids"), null);
  });

  test("an edit that removed EVERY image still says so", () => {
    /*
     * As on the volunteering form: the keep-set used to be written only when
     * it was non-empty, so removing the last image sent nothing and
     * `MediaKeepSet` kept them all. The scalar sentinel is the empty set's
     * only multipart representation.
     */
    const { formData } = buildLearnServePayload({
      ...args,
      isUpdate: true,
      id: 42,
      existingImageIds: [],
      values: values(),
    });
    assert.equal(get(formData, "existing_image_ids"), "none");
    assert.equal(
      entries(formData).filter(([k]) => k === "existing_image_ids[]").length,
      0
    );
    // Not a repost — nothing is cloned from a source record.
    assert.equal(get(formData, "opportunity_id"), null);
  });

  test("returns the normalized dates and times the caller reuses", () => {
    // The caller uses these for time-slot bookkeeping after the save; deriving
    // them a second time is how the two ends of one submission drift apart.
    const result = buildLearnServePayload({ ...args, values: values() });
    assert.equal(result.formattedStartDate, "2027-02-01");
    assert.equal(result.formattedEndDate, "2027-02-05");
    assert.equal(result.formattedStartTime, "09:00:00");
    assert.equal(result.formattedEndTime, "12:00:00");
  });

  test("a paid development opportunity preserves its optional sponsors", () => {
    const { sponsorIds } = buildLearnServePayload({
      ...args,
      values: values({
        is_paid: "true",
        price: "50",
        sponsors: [{ sponsorId: "9", position: 1 }],
      }),
    });
    assert.deepEqual(sponsorIds, ["9"]);
  });

  test("a free opportunity keeps its chosen sponsors and drops empty rows", () => {
    const { sponsorIds } = buildLearnServePayload({
      ...args,
      values: values({
        sponsors: [
          { sponsorId: "9", position: 1 },
          { sponsorId: "", position: 2 },
        ],
      }),
    });
    assert.deepEqual(sponsorIds, ["9"]);
  });
});
