/**
 * The event form's `initialValues`, as a pure function of the loaded record.
 *
 * Lifted out of `useEventForm` so the field-by-field mapping from the API
 * payload can be tested without React — the interest-id regression below is
 * exactly the kind of mistake that is invisible in a hook and obvious in a
 * table of assertions.
 */

import type { EventDetailRecord } from "@/features/events/eventRecord";
import type { EventFormValues } from "./eventFormTypes";

/** `"HH:MM"` from the API's `"HH:MM:SS"`. */
function clockTime(value: string | null | undefined): string {
  return value?.split(":")?.slice(0, 2).join(":") || "";
}

export function buildEventInitialValues(
  event: EventDetailRecord | undefined,
  /**
   * Whether the stored English title is one the organizer actually wrote. An
   * event saved without the English panel stores the Arabic title in both
   * columns; prefilling it would show Arabic in the English field.
   */
  hasDistinctEnglishTitle = true,
): EventFormValues {
  return {
    title_ar: event?.title_ar || "",
    title_en: hasDistinctEnglishTitle ? event?.title_en || "" : "",
    description_ar: event?.description_ar || "",
    description_en: event?.description_en || "",
    age: [
      event?.from_age ? Number(event.from_age) : null,
      event?.to_age ? Number(event.to_age) : null,
    ],
    gender: event?.gender_display?.id ? String(event.gender_display.id) : "",
    startDate: event?.start_date || "",
    endDate: event?.end_date || "",
    startTime: clockTime(event?.start_time),
    endTime: clockTime(event?.end_time),
    event_type: event?.event_type_display?.id
      ? String(event.event_type_display.id)
      : "",
    participation_type: event?.participation_type_display?.id
      ? String(event.participation_type_display.id)
      : "",
    participation_type_value_en:
      event?.participation_type_display?.value_en || "",
    location: event?.map_desc || "",
    registration_link: event?.registration_link || "",
    /* `interests`, not `interest_display`. `websiteInterestDisplay()` emits
     only `value_en`/`value_ar` — there is no `id` on that key — so this read
     produced one literal `"undefined"` per saved interest: the picker showed
     nothing ticked on edit, and the submit appended
     `interest_ids[]=undefined`, which fails the `integer` rule. The
     `interest_ids[]` fallback then retried without the tags, so an edit
     silently cleared them. The detail-only `interests` array carries the
     `master_choices` id that `Rule::in(MasterChoice … 'event_interest')`
     accepts, and that `tagOptions` keys on. Covered by
     `tests/eventInterestSeeding.test.ts`. */
    _interests: event?.interests?.map((interest) => String(interest.id)) || [],
    card_image: [],
    event_images: [],
    location_url: event?.location_url || "",
    latitude: event?.latitude?.toString() || "",
    longitude: event?.longitude?.toString() || "",
    sponsors: event?.event_sponsor_images?.length
      ? event.event_sponsor_images.map((sponsor, index) => ({
          /* Always nested or null — see the sponsor-extraction effect above. */
          sponsorId: String(sponsor.organization?.id || ""),
          position: index + 1,
        }))
      : [{ sponsorId: "", position: 1 }],
  };
}

/**
 * A13: a repost is new content, so it keeps only the tags the picker offers.
 * The seeded `_interests` carry every tag of the source — including a held
 * fallback «عام» the picker no longer shows — and the API accepts the source's
 * held tags on a republish, so the hidden tag would travel to the new event.
 * An empty option list (still loading) keeps the ids untouched.
 */
export function offeredInterestIds(ids: string[], options: ReadonlyArray<{ id: string }>): string[] {
  if (options.length === 0) return ids;
  const offered = new Set(options.map((option) => option.id));
  return ids.filter((id) => offered.has(id));
}
