import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { toWhatsAppLink } from "@/lib/whatsapp";
import { withWebScheme } from "@/features/events/eventLifecycle";
import {
  OPPORTUNITY_NATIONALITY_FIELD_LIVE,
  opportunityNationalityToLegacyFlag,
  type OpportunityNationality,
} from "@/data/Constants";
import type { PublishPermissions } from "@/lib/publishPermissions";
import type { LearnServeFormValues } from "./learnServeFormTypes";
import { appendImageKeepSet } from "@/features/shared/imageKeepSet";

interface BuildPayloadArgs {
  values: LearnServeFormValues;
  /** Editing an existing record rather than publishing a new one. */
  isUpdate: boolean;
  /** Reposting: a new record copying selected announcement media, never attendance. */
  isRepublish?: boolean;
  id?: string | number | null;
  /** Ids of already-stored images the organizer chose to keep. */
  existingImageIds: number[];
  publishPermissions: PublishPermissions;
  internshipTypeId?: string;
  courseTypeId?: string;
  onlineFormatId?: string;
}

/**
 * The multipart body for creating or updating a development opportunity.
 *
 * Every rule about *what the server receives* lives here — the paid/free
 * matrix, the licence keep-or-remove signal, the republish media contract, and
 * the certificate field that only applies to a course or internship. It was
 * inline in the form's submit handler, which meant the wire format could only
 * be read by scrolling through error handling and navigation.
 *
 * The body itself is `FormData` rather than an object because the update route
 * reaches the backend by `_method` spoofing, which Laravel only reads out of a
 * multipart body.
 *
 * The four normalized date/time strings and the sponsor id list come back with
 * it: the caller needs the same values for the time-slot bookkeeping and the
 * sponsor sync that follow the save, and deriving them twice is how the two
 * ends of one submission drift apart.
 */
export interface LearnServePayload {
  formData: FormData;
  formattedStartDate: string;
  formattedEndDate: string;
  formattedStartTime: string;
  formattedEndTime: string;
  /** Optional sponsors for free and paid development alike. */
  sponsorIds: string[];
}

export function buildLearnServePayload({
  values,
  isUpdate,
  isRepublish,
  id,
  existingImageIds,
  publishPermissions,
  internshipTypeId,
  courseTypeId,
  onlineFormatId,
}: BuildPayloadArgs): LearnServePayload {
  const formData = new FormData();

  const formattedStartDate = formatDateToYYYYMMDD(values.startDate);
  const formattedEndDate = formatDateToYYYYMMDD(values.endDate);
  const formattedStartTime = `${values.startTime}:00`;
  const formattedEndTime = `${values.endTime}:00`;

  // The certificate uses an independently authored English title.
  const arabicTitle = values.title_ar.trim();
  formData.append("title_ar", arabicTitle);
  formData.append("title_en", values.title_en.trim());
  formData.append("description_ar", values.description_ar);
  formData.append(
    "description_en",
    values.description_ar
  );
  formData.append("start_date", formattedStartDate);
  formData.append("end_date", formattedEndDate);
  formData.append("format_id", values.learnServeFormat);
  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("primary_language", values.primary_language);
  /* VAL-DEV-01 — the API validates `date_format:H:i`, which refuses the
     seconds the `HH:mm:00` strings above carry (those stay as they are for the
     timings step, which reads them back). The admin dashboard trims to five
     characters for the same reason. */
  formData.append("start_time", formattedStartTime.slice(0, 5));
  formData.append("end_time", formattedEndTime.slice(0, 5));
  // The API's `boolean` validation rule only accepts 1/0 (or "1"/"0"),
  // not the literal strings "true"/"false".
  // Never send paid where the matrix forbids it — an internship, or a
  // volunteer team — even if an older value is still in the form.
  const isPaidOpportunity =
    values.is_paid === "true" &&
    publishPermissions.developmentPaid &&
    !(internshipTypeId && values.learningType === internshipTypeId);
  /*
   * BE-77: the four-way audience. The new key is only sent once the
   * backend accepts it — `RejectsUnknownWriteKeys` 422s the whole form
   * otherwise — and `is_kuwaitis` goes alongside it either way, so an
   * older API and an updated one both get an answer they understand.
   */
  const grantsCertificate =
    (!!internshipTypeId && values.learningType === internshipTypeId) ||
    (!!courseTypeId && values.learningType === courseTypeId);
  const nationality = (grantsCertificate ? values.opportunity_nationality : "all") as OpportunityNationality;
  if (OPPORTUNITY_NATIONALITY_FIELD_LIVE) {
    formData.append("opportunity_nationality", nationality);
  }
  formData.append(
    "is_kuwaitis",
    opportunityNationalityToLegacyFlag(nationality) ? "1" : "0"
  );
  formData.append("is_paid", isPaidOpportunity ? "1" : "0");
  // Only meaningful when paid. On the free branch the backend nulls the
  // column itself, so sending an empty string would just be noise.
  if (isPaidOpportunity) {
    formData.append("price", values.price);
  }
  formData.append("gender_id", values.gender);

  // Unconditional even though optional: an empty string reaches Laravel as
  // null (ConvertEmptyStringsToNull), which is how an edit clears it.
  formData.append("due_date", "");
    formData.append("registration_deadline_hours", values.registrationDeadlineHours || "");

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

  // 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");
  }

  // 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", String(id));
    appendImageKeepSet(formData, existingImageIds);
  } else if (id) {
    /* No `length > 0` guard — see `appendImageKeepSet`: an empty keep-set has
       to travel as the scalar sentinel, or removing the last image reads as
       "keep everything". */
    appendImageKeepSet(formData, existingImageIds);
  }

  // Creation sends `opportunity_images_*`; updates send `new_opportunity_images_*`
  values.opportunity_images.forEach((file, index) => {
    if (!(file instanceof File)) return;
    const prefix = isUpdate
      ? "new_opportunity_images"
      : "opportunity_images";
    formData.append(`${prefix}_${index}`, file);
    /* Read on create (`opportunity_images_is_after_completed_{i}`) and
       ignored on update: `storeAnnouncementImagesFromRequest()` hard-codes
       `false` for the `new_opportunity_images_` prefix. `"0"` is that same
       answer either way, so the two branches agree. */
    formData.append(`${prefix}_is_after_completed_${index}`, "0");
  });

  // PDF page 18: sponsors are optional for both free and paid development.
  const sponsorIds = [...new Set(values.sponsors.map(sponsor => sponsor.sponsorId).filter(Boolean))];

  // BE-65 — the contact belongs to the opportunity, not to its format, so
  // it is sent for in-person and online alike. Empty clears the column:
  // ConvertEmptyStringsToNull turns "" into null server-side, which is what
  // `['nullable', 'url']` expects.
  // A typed number goes out as a `wa.me` link (BE-171).
  formData.append("whatsapp_link", toWhatsAppLink(values.whatsappLink));

  if (values.learnServeFormat === onlineFormatId) {
    // The form accepts `www.…` (the Yup rule adds a scheme only to check it);
    // Laravel's `url` rule does not, so the scheme is added before sending.
    formData.append("link", withWebScheme(values.meetingLink));
  } else {
    formData.append("map_desc", values.location || "");
    formData.append("location_url", withWebScheme(values.location_url));
    if (values.latitude) formData.append("latitude", values.latitude);
    if (values.longitude) formData.append("longitude", values.longitude);
  }

  /*
   * Only courses and internships grant a certificate — a class/workshop or
   * a consultation must never carry a certificate type. The field is
   * already hidden for those types, but Formik keeps whatever was picked
   * before the type was switched, and an edited opportunity starts from
   * whatever the record already had. Sending an empty value clears the
   * column (Laravel's ConvertEmptyStringsToNull turns it into `null`,
   * which the API accepts), so switching a course to a workshop actually
   * removes its certificate instead of leaving it behind.
   */
  formData.append(
    "certificate_type_id",
    grantsCertificate ? values.certificateType || "" : ""
  );
  if (values.learningType) {
    formData.append("learning_type_id", values.learningType);
  }

  return {
    formData,
    formattedStartDate,
    formattedEndDate,
    formattedStartTime,
    formattedEndTime,
    sponsorIds,
  };
}
