/**
 * The two opportunity payloads, as the backend actually emits them.
 *
 * There are **two resource families** for the same database rows, and telling
 * them apart is the entire reason this file exists:
 *
 * | Served by | Resource | Reached through |
 * |---|---|---|
 * | list / card | `Website\WebsiteVolunteerOpportunityResource`, `Website\WebsiteLearnServeOpportunityResource` | `GET /list-volunteer-opportunities/`, `/learn-serve-opportunities/`, `/list-all-opportunities/`, `/list-user-opportunities/` |
 * | detail | `Opportunity\VolunteerOpportunityResource`, `Opportunity\LearnServeOpportunityResource` | `GET /opportunities/{id}/details/`, `/learn-serve-opportunities/{id}/` |
 *
 * They are not a subset relationship. The same key name means different things
 * in each family, and every one of these differences is a way to read
 * `undefined` without a type error:
 *
 * - **`created_by`** is `{ id }` **and nothing else** on a card
 *   (`websiteCreatorId()`), but carries the name, photo, `is_public` and five
 *   social links on detail (`createdByPayload()`).
 * - **`interest_display`** has **no `id`** on a card (`websiteInterestDisplay()`
 *   emits only the two labels) and is always an array; on detail it has `id`
 *   and `choice_type` but is **`null`, not `[]`, when the list is empty**
 *   (`interestDisplayPayload()` returns null for an empty set).
 * - **`opportunity_images`** has **no `id`** on a card (`websiteImageList()`),
 *   and `{ id, image, is_after_completed }` on detail.
 * - **Counts and ages are `ar_num()`-wrapped on cards only.** On a card
 *   `participants_needed` is `number | string`; on detail it is a raw
 *   `number`. See `ArabicNumeric`.
 * - **`time_slots`** on a card has no `id` and no `hours`; the detail list has
 *   both, and Learn & Serve calls its version `timeslots_display` with a
 *   different element shape again (`LearnServeTimeSlotResource`).
 *
 * Fields are typed from the resource, so `null` here means the resource can
 * really emit null — not that the value is merely optional.
 */

import type {
  ArabicNumeric,
  CreatorIdRecord,
  EnArLabel,
  MasterChoiceDisplay,
  RegisteredUserIdRecord,
  WebsiteChoiceDisplay,
} from "@/features/shared/apiPrimitives";

/** `'volunteer_opportunity' | 'learn_serve_opportunity'` — a literal on the resource. */
export type OpportunityKind = "volunteer_opportunity" | "learn_serve_opportunity";

/**
 * `resolvedOpportunityStatus()`. Not a closed enum on the PHP side, so it is
 * widened — but these are the four values the frontend branches on.
 */
export type OpportunityStatus =
  | "upcoming"
  | "inprogress"
  | "completed"
  | "cancelled"
  | (string & {});

/** `actionState()` — one computed state so every screen renders the same button. */
export type OpportunityActionState = string;

/** `relationshipTags()` — the viewer's relationship to this row. */
export type RelationshipTag = "organizer" | "sponsor" | "registered" | "attended";

/** `profileActivityTag()`. Null unless the row was built for a profile tab. */
export type ProfileActivityTag = "provider" | "participant" | "attended" | "registered";

/** `ownerAttendanceStatus()`. Null when not applicable. */
export type OwnerAttendanceStatus = "attended" | "absent" | "upcoming";

/** One image on a **card** payload: `websiteImageList()` — no `id`. */
export interface OpportunityCardImage {
  /** `getimg()`, or null when the column is empty. */
  image: string | null;
}

/** One image on a **detail** payload: `opportunityImagesPayload()`. */
export interface OpportunityDetailImage {
  id: number;
  image: string | null;
  is_after_completed: boolean;
}

/** An interest on a **card**: only the labels, no id. */
export interface OpportunityCardInterest {
  value_en?: string | null;
  value_ar?: string | null;
}

/** An interest on a **detail** payload: `interestDisplayPayload()`. */
export interface OpportunityDetailInterest {
  id: number;
  choice_type: string;
  value_en?: string | null;
  value_ar?: string | null;
}

/** The detail-only `interests` array: `tagPayload()`. The only key that can seed the picker. */
export interface OpportunityTagRecord {
  id: number;
  name_en?: string | null;
  name_ar?: string | null;
  interest_type?: string | null;
}

/** A day on a **card**'s `time_slots`. No `id`, no `hours`. */
export interface OpportunityCardTimeSlot {
  date: string | null;
  start_time: string | null;
  end_time: string | null;
}

/** A day on a **detail** payload's `time_slots`. */
export interface OpportunityDetailTimeSlot extends OpportunityCardTimeSlot {
  id: number;
  hours: number | null;
}

/** A sponsor slot: `opportunitySponsorImagesPayload()`, sorted by `position`. */
export interface OpportunitySponsorImage {
  id: number;
  /** The sponsoring organisation's avatar, or null when it has none. */
  image: string | null;
  organization: { id: number; full_name: string } | null;
  position: number | null;
}

/** The creator on a **detail** payload: `createdByPayload()`. */
export interface OpportunityCreatorRecord {
  id: number;
  /** `fullName()` — `''` rather than null when there is no name to show. */
  full_name: string;
  nickname: string | null;
  profile_pic: string | null;
  /** Drives the private-vs-public profile route. Defaults false for an org. */
  is_public: boolean;
  gender_display: MasterChoiceDisplay | null;
  instagram_link: string | null;
  whatsapp_link: string | null;
  linkedin_link: string | null;
  facebook_link: string | null;
  twitter_link: string | null;
}

/** `selfAttendanceState()`. Null when the viewer is not registered. */
export interface SelfAttendanceState {
  next_action?: "check_in" | "check_out" | null;
  checked_out_at?: string | null;
  can_scan?: boolean;
  /** Today's one presence scan is in. */
  attended_today: boolean;
  /** ISO 8601 — when today's attendance was recorded; null until then. */
  scanned_at: string | null;
  /** BE-121 — attended days counted toward the certificate. */
  attended_count: number;
}

/** Keys both card families share, with the card-family types. */
interface OpportunityCardCommon {
  id: number;
  opportunity_type: OpportunityKind;
  title_en: string | null;
  title_ar: string | null;
  opportunity_status: OpportunityStatus;
  /** `formatDateTime()` — `Y-m-d\TH:i:s.u\Z`. */
  registration_deadline_hours?: number | null;
  due_date: string | null;
  /** `formatDate()` — `Y-m-d`. */
  start_date: string | null;
  end_date: string | null;
  start_time: string | null;
  end_time: string | null;
  from_age: ArabicNumeric | null;
  to_age: ArabicNumeric | null;
  location_en: string | null;
  location_ar: string | null;
  /** Falls back to `location_ar` then `location_en` when unset. */
  map_desc: string | null;
  lat: number | null;
  lng: number | null;
  /** BE-60: the location URL only — never the WhatsApp contact link. */
  location_url: string | null;
  is_registration_closed: boolean;
  is_registration_open: boolean;
  can_register_while_running?: boolean;
  participants_needed: ArabicNumeric | null;
  registered_volunteers_count: ArabicNumeric;
  opportunity_images: OpportunityCardImage[];
  created_by: CreatorIdRecord | null;
  interest_display: OpportunityCardInterest[];
  is_supports_disabled: boolean;
  is_urgent: boolean;
  is_relief: boolean;
  is_registered: boolean;
  action_state: OpportunityActionState;
  is_full: boolean;
  has_started: boolean;
  has_ended: boolean;
  all_registered_user: RegisteredUserIdRecord[];
  relationship_tags: RelationshipTag[];
  profile_activity_tag: ProfileActivityTag | null;
  owner_attendance_status: OwnerAttendanceStatus | null;
}

/** `WebsiteVolunteerOpportunityResource` — the volunteer card/list row. */
export interface VolunteerOpportunityCardRecord extends OpportunityCardCommon {
  opportunity_type: "volunteer_opportunity";
  /** BE-58: without this, `start_date..end_date` reads as an unbroken range. */
  has_custom_schedule: boolean;
  time_slots: OpportunityCardTimeSlot[];
  is_emergency: boolean;
  is_public: boolean;
  volunteer_category: string | null;
  volunteer_category_display: EnArLabel | null;
  /** Null unless the category counts beneficiaries. */
  beneficiaries_count: ArabicNumeric | null;
}

/** `WebsiteLearnServeOpportunityResource` — the learn & serve card/list row. */
export interface LearnServeOpportunityCardRecord extends OpportunityCardCommon {
  opportunity_type: "learn_serve_opportunity";
  /** BE-65 — an ungated contact number, unlike the gated `link`. */
  whatsapp_link: string | null;
  is_paid: boolean;
  price: number | null;
  format_display: WebsiteChoiceDisplay | null;
  learning_type_id: number | null;
  format_id: number | null;
  certificate_type_id: number | null;
  requires_check_in: boolean;
  certificate_type_display: WebsiteChoiceDisplay | null;
  learning_type_display: WebsiteChoiceDisplay | null;
}

/** Either card row. Discriminate on `opportunity_type`. */
export type OpportunityCardRecord =
  | VolunteerOpportunityCardRecord
  | LearnServeOpportunityCardRecord;

/** Keys both detail resources share. */
interface OpportunityDetailCommon {
  unassigned_slots_remaining?: number | null;
  id: number;
  opportunity_status: OpportunityStatus;
  approval_status: string | null;
  /** BE-80 C — the admin's reason, emitted for the owner only. */
  rejected_reason: string | null;
  title_en: string | null;
  title_ar: string | null;
  description_en: string | null;
  description_ar: string | null;
  registration_deadline_hours?: number | null;
  due_date: string | null;
  start_date: string | null;
  end_date: string | null;
  opportunity_nationality: string | null;
  /** Raw here — the detail resources do **not** apply `ar_num()`. */
  participants_needed: number | null;
  from_age: number | null;
  to_age: number | null;
  start_time: string | null;
  end_time: string | null;
  /** The unconverted column; `lat`/`lng` are the numeric pair. */
  latitude: string | number | null;
  longitude: string | number | null;
  lat: number | null;
  lng: number | null;
  location_en: string | null;
  location_ar: string | null;
  map_desc: string | null;
  location_url: string | null;
  /** The online meeting URL — gated to registered participants. */
  link: string | null;
  is_calendar: boolean;
  primary_language: string | null;
  registered_volunteers_count: number;
  is_registration_closed: boolean;
  is_registration_open: boolean;
  can_register_while_running?: boolean;
  is_kuwaitis: boolean;
  license_image: string | null;
  /** **Null, not `[]`, when there are no interests.** */
  interest_display: OpportunityDetailInterest[] | null;
  all_registered_user: RegisteredUserIdRecord[];
  is_saved_to_calendar: boolean;
  calendar_id: number | null;
  action_state: OpportunityActionState;
  is_full: boolean;
  has_started: boolean;
  has_ended: boolean;
  relationship_tags: RelationshipTag[];
  preparation_valid_until: string | null;
  requires_check_in?: boolean;
  qr_attendance_enabled: boolean;
  manual_attendance_enabled: boolean;
  /**
   * BE-101 — the organizer's "the scan must prove they are on site" choice.
   *
   * It was dormant when this type was written (no resource emitted it, no
   * column held it). It is real now: present on the opportunity card and
   * detail, and accepted on create/update as `['sometimes','boolean']`. The
   * server owns the radius and the distance check; see
   * `features/opportunities/attendanceLocation.ts`.
   *
   * Still optional on the type, because an older cached payload and the
   * learn-serve record do not carry it.
   */
  requires_attendance_location?: boolean | number | null;
}

/** `Opportunity\VolunteerOpportunityResource` — `GET /opportunities/{id}/details/`. */
export interface VolunteerOpportunityDetailRecord extends OpportunityDetailCommon {
  opportunity_type: "volunteer_opportunity";
  volunteer_hours_per_day: number | null;
  /** Defaults to 70 when the column is null. */
  certificate_attendance_percentage: number;
  gender_display: MasterChoiceDisplay | null;
  is_public: boolean;
  is_interview_needed: boolean;
  is_urgent: boolean;
  is_emergency: boolean;
  is_relief: boolean;
  is_supports_disabled: boolean;
  interests: OpportunityTagRecord[];
  opportunity_images: OpportunityDetailImage[];
  opportunity_sponsor_images: OpportunitySponsorImage[];
  created_by: OpportunityCreatorRecord | null;
  user_type: string | null;
  /** Always the real detail URL — never a bare invite UUID. */
  registration_link: string;
  after_completed_images_count: number;
  is_registered: boolean;
  total_roles: number;
  has_scan_permission: boolean;
  manual_tracking: boolean;
  preparation_valid_until_at: string | null;
  is_preparation_window_closed: boolean;
  preparation_reopened_until: string | null;
  has_custom_schedule: boolean;
  time_slots: OpportunityDetailTimeSlot[];
  volunteer_category: string | null;
  volunteer_category_display: EnArLabel | null;
  beneficiaries_count: number | null;
  supports_beneficiaries_count: boolean;
  /** BE-61 Part A. Null when the viewer is not registered. */
  self_attendance: SelfAttendanceState | null;
  /** BE-69 — true for the organizer *or* a volunteer holding the permission. */
  can_manage_attendance: boolean;
}

/** `Opportunity\LearnServeOpportunityResource` — `GET /learn-serve-opportunities/{id}/`. */
export interface LearnServeOpportunityDetailRecord extends OpportunityDetailCommon {
  opportunity_type: "learn_serve_opportunity";
  whatsapp_link: string | null;
  is_paid: boolean;
  price: number | null;
  payout_after_fee: number | null;
  /** BE-71 — travels with `payout_after_fee` so the two cannot disagree. */
  platform_fee_percentage: number | null;
  learning_type_id: number | null;
  format_id: number | null;
  certificate_type_id: number | null;
  learning_type_display: MasterChoiceDisplay | null;
  format_display: MasterChoiceDisplay | null;
  certificate_type_display: MasterChoiceDisplay | null;
  gender_display: MasterChoiceDisplay | null;
  interests: OpportunityTagRecord[];
  opportunity_images: OpportunityDetailImage[];
  /** Withheld (`[]`) for a paid opportunity — a sponsor funds a free one. */
  opportunity_sponsor_images: OpportunitySponsorImage[];
  after_completed_images_count: number;
  created_by: OpportunityCreatorRecord | null;
  user_type: string | null;
  /** `LearnServeTimeSlotResource::collection()` — a different shape again. */
  timeslots_display: LearnServeTimeSlotRecord[];
  is_registered: boolean;
  is_attended: boolean;
}

/**
 * `Opportunity\LearnServeTimeSlotResource` — the `timeslots_display` element
 * and the whole of `GET /time-slots/`.
 *
 * Note the key name: the opportunity id arrives under **`opportunity`**, as a
 * bare integer, not `opportunity_id` and not a nested object. That is the same
 * trap `VolunteerProfileRecord.user` carries, and it is why this type is
 * transcribed rather than guessed — `slot.opportunity_id` type-errors here
 * instead of silently reading `undefined`.
 *
 * The **write** side of the same endpoint uses the other name:
 * `LearnServeTimeSlotController::store()` validates `opportunity_id`, and the
 * frontend sending `opportunity` was a 422 on every create (see
 * `TimeSlotPayload` in `useTimeSlotSubmit`). So this resource reads
 * `opportunity` and writes `opportunity_id` — they are genuinely different
 * names for the same column, not a transcription slip.
 */
export interface LearnServeTimeSlotRecord {
  id: number;
  /** The opportunity's id. A number, under this name. */
  opportunity: number;
  /** `Y-m-d`. */
  date: string | null;
  start_time: string | null;
  end_time: string | null;
  participants_needed: number | null;
  created_at: string | null;
  updated_at: string | null;
  /** Denormalised from the parent, so a slot row can render a range alone. */
  opportunity_start_date: string | null;
  opportunity_end_date: string | null;
  opportunity_start_time: string | null;
  opportunity_end_time: string | null;
}

/**
 * Narrowing for the mixed list `GET /list-all-opportunities/` returns.
 *
 * The controller only makes that list homogeneous when the caller passes
 * `opportunity_type` or a type-scoped `filter_type` — it silences the other
 * two queries with `whereRaw('0 = 1')`. That is a *runtime* guarantee no type
 * can see, so the three screens reading this endpoint narrow explicitly
 * instead of asserting. If a filter is ever changed or dropped, the row simply
 * stops matching rather than being read as the wrong shape.
 *
 * The discriminator is deliberately `opportunity_type`: an event row does not
 * carry that key at all, which is exactly the fallback the controller's own
 * sort comparator uses (`$item['event_status'] ?? $item['opportunity_status']`).
 */
export function isOpportunityCard(
  row: { opportunity_type?: unknown } | null | undefined
): row is OpportunityCardRecord {
  return (
    row?.opportunity_type === "volunteer_opportunity" ||
    row?.opportunity_type === "learn_serve_opportunity"
  );
}

/** A volunteer card in the mixed list. */
export function isVolunteerOpportunityCard(
  row: { opportunity_type?: unknown } | null | undefined
): row is VolunteerOpportunityCardRecord {
  return row?.opportunity_type === "volunteer_opportunity";
}

/** A learn & serve card in the mixed list. */
export function isLearnServeOpportunityCard(
  row: { opportunity_type?: unknown } | null | undefined
): row is LearnServeOpportunityCardRecord {
  return row?.opportunity_type === "learn_serve_opportunity";
}

/**
 * An **event** row in the mixed list. `WebsiteEventResource` stamps
 * `opportunity_type: 'event'` (`Website/WebsiteEventResource.php:83`); older
 * payloads carried no `opportunity_type` at all, so both are accepted. Testing
 * only for the missing key filtered out every event and left the profile
 * Events tab permanently empty.
 *
 * Typed against the caller's own event shape rather than importing
 * `EventRecord`, so this module stays free of a dependency on the events
 * feature.
 */
export function isEventCard<T extends { opportunity_type?: unknown }>(
  row: T | null | undefined
): row is Exclude<T, { opportunity_type: OpportunityKind }> {
  return !!row && (row.opportunity_type === undefined || row.opportunity_type === "event");
}
