/**
 * The event payload the website endpoints return.
 *
 * Transcribed from `WebsiteEventResource::toArray()` — the resource
 * `EventController::index()` and `::show()` both answer with. The sibling
 * `EventResource` is the *admin* shape and uses different key names
 * (`images` / `sponsor_images` rather than `event_images` /
 * `event_sponsor_images`); nothing in this app reads it, so it is not modelled
 * here. Getting those two confused is worth guarding against: three local
 * `EventData` interfaces were each a partial, drifting view of this one shape.
 *
 * Two properties of the payload the types below encode deliberately:
 *
 * - **`detail`**. `show()` constructs the resource with `detail: true`, which
 *   merges in a second block of keys. `index()` does not. `EventRecord` is the
 *   list shape; `EventDetailRecord` adds the detail-only block, so a reader of
 *   a list row cannot reach for a description that is not there.
 * - **Numbers arrive as strings in Arabic.** Every count and age on the
 *   resource is wrapped in `ar_num()`, which returns Eastern Arabic digits when
 *   the request locale is `ar`. They are typed `number | string` to match.
 *   `lib/api/client.ts` runs `normalizeDigitsDeep` over every response, so a
 *   reader sees Western digits in practice — but only through the axios client,
 *   which is why the string half of the union stays.
 */

/** One uploaded event image. `websiteImageListWithIds()`. */
export interface EventImageRecord {
  id: number;
  /** `getimg()` — an absolute URL, or null when the column is empty. */
  image: string | null;
}

/**
 * A choice embedded under a `*_display` key on a website resource.
 *
 * Not `ChoiceDisplay` from `lib/choices.ts`: `websiteChoicePayload()` runs the
 * four keys through `array_filter(… !== null)`, so any of them can be *absent*
 * rather than null, and `choice_type` is only present when the caller passed
 * one. Only `event_type_display` does.
 */
export interface WebsiteChoiceDisplay {
  id?: number;
  choice_type?: string;
  value_en?: string;
  value_ar?: string;
}

/**
 * An interest as `interest_display` carries it.
 *
 * `websiteInterestDisplay()` emits **only the two labels — there is no `id`**,
 * and it is built from the legacy `interests` relation rather than
 * `effectiveInterests()`. Anything that needs an interest's id must read the
 * detail-only `interests` array instead; seeding the edit form from this key
 * was a bug (see `EventTagRecord`).
 */
export interface EventInterestDisplay {
  value_en?: string | null;
  value_ar?: string | null;
}

/**
 * An interest as the detail-only `interests` array carries it: `tagPayload()`.
 *
 * `effectiveInterests()` prefers the `masterInterests` relation and falls back
 * to legacy `interests`, so `id` is a `master_choices` id whenever master rows
 * exist — which is the id `interest_ids.*` validates against on create/update
 * (`Rule::in(MasterChoice … 'event_interest')`). This is therefore the only key
 * on the payload that can seed the interest picker.
 */
export interface EventTagRecord {
  id: number;
  name_en?: string | null;
  name_ar?: string | null;
  interest_type?: string | null;
}

/** One sponsor slot. Detail only. */
export interface EventSponsorImageRecord {
  id: number;
  image: string | null;
  position: number;
  /**
   * Always a nested object or null — never a bare id. The `? [...] : null`
   * in the resource admits no third form, which is why the id-only branch the
   * event form carried for this key could not run.
   */
  organization: {
    id: number;
    /** `company_name ?: nickname` — never null, though it may be `""`. */
    full_name: string;
    profile_pic: string | null;
  } | null;
}

/**
 * `websiteEventCreator()`, on the detail payload only.
 *
 * **`id` is the creator's `users.id`, not the organization profile's.** This is
 * worth stating because `events.created_by` is a foreign key to
 * `organization_profiles` — the admin-side `EventResource` emits that raw column
 * under the same key name — while the website resource resolves it through
 * `$event->organization?->user` first. The ten frontend sites that compare
 * `created_by.id === currentUser.id` are therefore correct, and would silently
 * stop being correct if a screen were ever pointed at `EventResource`.
 *
 * `volunteer_opportunities.created_by` and `learn_serve_opportunities.created_by`
 * are `users.id` in the column itself, so the same comparison holds there for a
 * different reason.
 */
/** The five link fields on a creator block — the keys the aside may read. */
export type EventCreatorSocialKey =
  | "facebook_link"
  | "twitter_link"
  | "whatsapp_link"
  | "instagram_link"
  | "linkedin_link";

export interface EventCreatorRecord {
  id: number;
  full_name?: string;
  profile_pic?: string | null;
  is_public?: boolean;
  facebook_link?: string | null;
  twitter_link?: string | null;
  whatsapp_link?: string | null;
  instagram_link?: string | null;
  linkedin_link?: string | null;
}

/** The list shape: every key `WebsiteEventResource` returns unconditionally. */
export interface EventRecord {
  /** Canonical server clock fields (BE-188); legacy daily times remain supported. */
  start_at?: string | null;
  end_at?: string | null;
  id: number;
  opportunity_type: "event";
  /* Both title columns are `->nullable()`, so a record really can have no
     title in one or both languages — several card components used to declare
     them `string` and index straight into them. */
  title_en: string | null;
  title_ar: string | null;
  /** `resolvedOpportunityStatus()`. */
  /** Column default `upcoming`, so never null. */
  event_status: string;
  due_date: string | null;
  /** `Y-m-d`. Both columns are NOT NULL. */
  start_date: string;
  end_date: string;
  /** `H:i:s` as stored — the form slices the first two parts off. */
  start_time: string | null;
  end_time: string | null;
  registration_required: boolean;
  registered_volunteers_count: number | string | null;
  participants_needed: number | string | null;
  /** Column default 0. */
  view_count: number | string;
  location_en: string | null;
  location_ar: string | null;
  /** `map_desc ?: location_ar ?: location_en` — the map picker's label. */
  map_desc: string | null;
  /** Numbers, unlike `latitude`/`longitude` below, which are the raw columns. */
  lat: number | null;
  lng: number | null;
  /** BE-60: deliberately not a fallback to `registration_link`. */
  location_url: string | null;
  is_registration_closed: boolean;
  is_registration_open: boolean;
  event_images: EventImageRecord[];
  /** The card image (`license_image`), else the first gallery photo; null when neither. */
  cover_image?: string | null;
  /** Owner-only (BE-106): `pending` | `approved` | `rejected`; null for everyone else. */
  approval_status?: string | null;
  rejected_reason?: string | null;
  participation_type_display: WebsiteChoiceDisplay | null;
  event_type_display: WebsiteChoiceDisplay | null;
  interest_display: EventInterestDisplay[];
  /** `{ id }` on a list row; the fuller creator object on a detail one. */
  created_by: EventCreatorRecord | null;
  is_creator: boolean;
  is_registered: boolean;
  is_saved_to_calendar: boolean;
  calendar_id: number | null;
  relationship_tags: string[];
  action_state: string | null;
  is_full: boolean;
  has_started: boolean;
  has_ended: boolean;
  /**
   * Detail-only today (`WebsiteEventResource` puts them under `$this->detail`);
   * optional here so the card's price pill reads them the moment the list
   * payload carries them too (BE-139).
   */
  paid_registration?: boolean | null;
  registration_fee?: number | string | null;
  /** Server capability flags (`OpportunityCapabilities`), owner-relevant; absent on older payloads. */
  can_delete?: boolean;
  can_request_deletion?: boolean;
}

/** The `detail: true` shape — what `GET /events/{id}/` answers with. */
export interface EventDetailRecord extends EventRecord {
  interests: EventTagRecord[];
  description_en: string | null;
  description_ar: string | null;
  primary_language: string | null;
  paid_registration: boolean;
  registration_fee: number | string | null;
  registration_link: string | null;
  /** The raw decimal columns, as strings. */
  latitude: string | null;
  longitude: string | null;
  from_age: number | string | null;
  to_age: number | string | null;
  attendance_type_display: WebsiteChoiceDisplay | null;
  gender_display: WebsiteChoiceDisplay | null;
  event_sponsor_images: EventSponsorImageRecord[];
  /** Only when registration is required *and* a capacity is set. */
  remaining_slots?: number | string;
}

/**
 * The title pair the delete / update confirmation modals take.
 *
 * Six components declared this inline as `{ title_en: string; title_ar: string }`
 * while both columns are `->nullable()` — so each of them would have rendered
 * the string `"null"` for a record saved with one title only. One definition,
 * honestly nullable, and `eventTitleText` below is the single place the fallback
 * is decided.
 */
export interface EventTitlePair {
  title_en: string | null;
  title_ar: string | null;
}

/**
 * The title to show for an event, or `""` when the record has neither.
 *
 * `""` rather than an i18n key on purpose: a missing i18n key renders the raw
 * key on screen, and these call sites are an image `alt` and a confirmation
 * sentence where an empty string degrades quietly.
 */
export function eventTitleText(
  event: EventTitlePair | null | undefined,
  language: string
): string {
  if (!event) return "";
  return (language === "ar" ? event.title_ar : event.title_en) ?? "";
}

/**
 * `EventResource` — the **admin** shape, which is what the three write
 * endpoints answer with (`POST /events/`, `POST /events/{id}/` carrying
 * `_method=PATCH`, and `POST /event/republish/{id}`). Everything else in this
 * file models `WebsiteEventResource`.
 *
 * The two resources are not interchangeable and the differences are the reason
 * this needs its own declaration rather than a reuse of `EventDetailRecord`:
 *
 *  - the collections are named `images` / `sponsor_images` here, not
 *    `event_images` / `event_sponsor_images`;
 *  - the raw foreign keys (`gender_id`, `event_type_id`, …) are exposed
 *    instead of the resolved `*_display` objects;
 *  - `interests` carries `tagPayload()` rows, same as the detail payload;
 *  - there is no `opportunity_type`, no `is_creator` and no `is_registered` —
 *    `relationship_tags` and `action_state` carry that instead;
 *  - `license_image` appears, and `registered_volunteers_count` does not.
 *
 * `images` and `sponsor_images` are **optional**, not merely nullable, and that
 * is a difference between the three writes rather than an abundance of caution:
 * both are `whenLoaded(...)`, and `EventController::store()` builds its resource
 * from the freshly created model with no eager loads, so a create response
 * omits both keys entirely while update and republish (which pass
 * `fresh([...])`) include them.
 */
export interface AdminEventRecord {
  id: number;
  title_en: string | null;
  title_ar: string | null;
  description_en: string | null;
  description_ar: string | null;
  /** The enum's `->value`, absent-as-null when the column is unset. */
  approval_status: string | null;
  deletion_status: string | null;
  /** `resolvedOpportunityStatus()`; the column defaults to `upcoming`. */
  event_status: string;
  from_age: number | string | null;
  to_age: number | string | null;
  /* Raw ids, where the website resource resolves `*_display` objects. */
  gender_id: number | null;
  attendance_type_id: number | null;
  event_type_id: number | null;
  participation_type_id: number | null;
  /** ISO 8601. */
  due_date: string | null;
  /** `Y-m-d`; both columns are NOT NULL. */
  start_date: string;
  end_date: string;
  start_time: string | null;
  end_time: string | null;
  registration_required: boolean;
  participants_needed: number | string | null;
  paid_registration: boolean;
  registration_fee: number | string | null;
  /** The raw decimal columns, as strings. */
  latitude: string | null;
  longitude: string | null;
  location_en: string | null;
  location_ar: string | null;
  /** `map_desc ?: location_ar ?: location_en`. */
  map_desc: string | null;
  /** Cast to float by the resource, unlike `latitude`/`longitude`. */
  lat: number | null;
  lng: number | null;
  location_url: string | null;
  is_registration_closed: boolean;
  is_registration_open: boolean;
  registration_link: string | null;
  /** `events.created_by` — the **organization profile** id, as a bare number. */
  created_by: number | null;
  /** `getimg()`, or null when no licence was uploaded. */
  license_image: string | null;
  view_count: number | string;
  primary_language: string | null;
  /** Absent on a create response. See the note above. */
  images?: EventImageRecord[];
  /** Absent on a create response. See the note above. */
  sponsor_images?: EventSponsorImageRecord[];
  interests: EventTagRecord[];
  interest_display: EventInterestDisplay[];
  created_at: string | null;
  updated_at: string | null;
  is_saved_to_calendar: boolean;
  calendar_id: number | null;
  action_state: string | null;
  is_full: boolean;
  has_started: boolean;
  has_ended: boolean;
  relationship_tags: string[];
}
