import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { toWhatsAppLink } from "@/lib/whatsapp";
import {
  ATTENDANCE_LOCATION_LIVE,
} from "@/features/opportunities/attendanceLocation";
import {
  OPPORTUNITY_NATIONALITY_FIELD_LIVE,
  VOLUNTEER_CATEGORY_WITH_BENEFICIARIES,
  opportunityNationalityToLegacyFlag,
  type OpportunityNationality,
} from "@/data/Constants";
import type { VolunteerFormValues } from "./volunteerFormTypes";
import { appendImageKeepSet } from "@/features/shared/imageKeepSet";

interface BuildVolunteerPayloadArgs {
  values: VolunteerFormValues;
  /** Reposting: a new record with selected announcement media, without old attendance. */
  isRepublish?: boolean;
  id?: string | null;
  /** Ids of already-stored images the organizer chose to keep. */
  existingImageIds: number[];
  /** The "about the opportunity" section is not shown for every publisher. */
  showOpportunitySection: boolean;
  /**
   * The accessibility tick-boxes. The *audience* left this set in BE-77 and
   * became its own select, which is why nationality is read off `values` while
   * these are still a separate list.
   */
  selectedCheckBoxes: string[];
  selectedLanguage: string;
}

export interface VolunteerPayload {
  formData: FormData;
  /** Synced separately after the record saves. */
  sponsorIds: string[];
}

/**
 * The multipart body for creating or updating a volunteering opportunity.
 *
 * Every rule about *what the server receives* lives here: the schedule's two
 * shapes, the public/private answer, the licence keep-or-remove signal and the
 * republish media contract. It was inline in the submit handler, which meant
 * the wire format could only be read by scrolling through navigation and error
 * handling.
 */
export function buildVolunteerPayload({
  values,
  isRepublish,
  id,
  existingImageIds,
  showOpportunitySection,
  selectedLanguage,
  selectedCheckBoxes,
}: BuildVolunteerPayloadArgs): VolunteerPayload {
  /*
   * BE-77: the audience left the tick-box set and became its own select, so it
   * is read from the form value rather than from `selectedCheckBoxes`. The new
   * key only goes on the wire once the backend accepts it —
   * `RejectsUnknownWriteKeys` 422s the whole publish on an unrecognised key —
   * while `is_kuwaitis` is sent either way.
   */
  const nationality = values.opportunity_nationality as OpportunityNationality;

    const checkboxValues = {
      is_relief: selectedCheckBoxes.includes("relief"),
      is_kuwaitis: opportunityNationalityToLegacyFlag(nationality),
      is_urgent: selectedCheckBoxes.includes("urgent"),
      // Emergency priority is independent of the "Outside Kuwait"
      // (`is_relief`) classification — it only drives the badge and the
      // top-of-list ordering the API applies.
      is_emergency: selectedCheckBoxes.includes("emergency"),
      is_supports_disabled: selectedCheckBoxes.includes("disabled"),
    };

    const formData = new FormData();

    // The English title is optional in the form but required by the API, so
    // an organizer who only wrote Arabic gets the Arabic title stored in
    // both columns. Sending an empty `title_en` instead would 422, and
    // sending a blank one would leave English-language screens headless.
    const arabicTitle = values.title_ar.trim();
    const englishTitle = arabicTitle;

    formData.append("title_ar", arabicTitle);
    formData.append("title_en", englishTitle);
    // Same rule as the title: the API requires both, so an organiser who
    // only wrote Arabic gets it stored in both columns rather than leaving
    // English-language visitors with an empty description.
    formData.append("description_ar", values.description_ar);
    formData.append(
      "description_en",
      values.description_ar
    );
    formData.append("due_date", "");
    formData.append("registration_deadline_hours", values.registrationDeadlineHours || "");
    formData.append("start_date", formatDateToYYYYMMDD(values.startDate));
    formData.append("end_date", formatDateToYYYYMMDD(values.endDate));

    /*
     * `time_slots` is the API's per-day schedule: with rows present only the
     * listed days count as running days, without them the whole
     * start_date..end_date range does. So scattered days send one row per
     * selected day, and consecutive days must actively send an empty value —
     * omitting the key entirely leaves a previously scattered schedule in
     * place, and the opportunity would keep running on days the organiser
     * has just replaced with a range.
     */
    if (values.scheduleMode === "scattered") {
      values.scheduleDates.forEach((day, index) => {
        formData.append(`time_slots[${index}][date]`, day);
        formData.append(`time_slots[${index}][start_time]`, values.startTime);
        formData.append(`time_slots[${index}][end_time]`, values.endTime);
      });
    } else {
      formData.append("time_slots", "");
    }

    formData.append("participants_needed", values.participantsNeeded);
    formData.append(
      "from_age",
      values.age[0] !== null ? values.age[0].toString() : ""
    );
    formData.append(
      "to_age",
      values.age[1] != null ? values.age[1].toString() : ""
    );
    formData.append("start_time", values.startTime);
    formData.append("end_time", values.endTime);
    formData.append("latitude", values.latitude);
    formData.append("longitude", values.longitude);
    // A typed number goes out as a `wa.me` link: the API only takes a URL
    // until BE-171 accepts a number.
    formData.append("link", toWhatsAppLink(values.link));
    formData.append("primary_language", selectedLanguage);
    formData.append("volunteer_hours_per_day", values.volunteerHoursPerDay);
    formData.append("gender_id", values.gender);
    formData.append(
      "is_public",
      showOpportunitySection
        ? values.isPrivate === "public"
          ? "1"
          : "0"
        : "1"
    );
    formData.append("map_desc", values.location);
    // Collected again: a pasted maps link is now the primary way to answer
    // "where", with the picker as the alternative. Sent even when empty so
    // an edit that swaps a link for a map pick clears the old one.
    formData.append("location_url", values.locationUrl.trim());
    if (ATTENDANCE_LOCATION_LIVE) {
      formData.append(
        "requires_attendance_location",
        values.requiresAttendanceLocation ? "1" : "0"
      );
    }
    formData.append("volunteer_category", values.volunteerCategory);
    // Beneficiaries only exist for charity work — send the field only then, so
    // a category switch doesn't push a stale count the backend would null out.
    if (
      values.volunteerCategory === VOLUNTEER_CATEGORY_WITH_BENEFICIARIES &&
      values.beneficiariesCount
    ) {
      formData.append("beneficiaries_count", values.beneficiariesCount);
    }

    Object.entries(checkboxValues).forEach(([key, value]) => {
      // The API's `boolean` validation rule only accepts 1/0 (or "1"/"0"),
      // not the literal strings "true"/"false".
      formData.append(key, value ? "1" : "0");
    });

    if (OPPORTUNITY_NATIONALITY_FIELD_LIVE) {
      formData.append("opportunity_nationality", nationality);
    }

    values._interests.forEach((interest) => {
      formData.append("interest_ids[]", interest);
    });

    // Explicitly clone the selected announcement media into the new record.
    // An empty keep-set still uses the scalar sentinel; old gallery media is excluded.
    if (isRepublish && id) {
      formData.append("opportunity_id", id);
      appendImageKeepSet(formData, existingImageIds);
    } else if (id) {
      /* Editing: only images with `is_after_completed === false` are kept.
         Through the shared helper, and no longer behind a `length > 0` guard —
         that guard meant removing the *last* image sent no key at all, which
         the backend reads as "keep everything". See `appendImageKeepSet`. */
      appendImageKeepSet(formData, existingImageIds);
    }

    values.opportunity_images.forEach((file, index) => {
      if (file instanceof File) {
        formData.append(`new_opportunity_images_${index}`, file);
        /* Ignored by the backend on this prefix, and kept anyway.
           `storeAnnouncementImagesFromRequest()` reads the companion flag only
           for the `opportunity_images_` prefix; for `new_opportunity_images_`
           it hard-codes `is_after_completed = false`, which is what `"0"` says
           — so the key is redundant rather than wrong. `RejectsUnknownWriteKeys`
           allows it through the `new_opportunity_images_*` pattern. Left in
           place because it states the intent at the only point where it is
           visible, and the two prefixes disagree about which one reads it. */
        formData.append(
          `new_opportunity_images_is_after_completed_${index}`,
          "0"
        );
      }
    });

    // License image: send a new file, or signal removal, or leave untouched.
    // Republish honours an explicit removal too — the backend's
    // RepublishMedia::apply() nulls the licence before it would clone the
    // source's, so the repost doesn't resurrect a removed document.
    if (values.license_image instanceof File && values.license_image.size > 0) {
      formData.append("license_image", values.license_image);
    } else if (id && values.license_image_removed) {
      formData.append("license_image_removed", "1");
    }

    const sponsorIds = values.sponsors
      .map((sponsor) => sponsor.sponsorId)
      .filter(Boolean);

  return { formData, sponsorIds };
}
