/**
 * The community payloads: posts and replies.
 *
 * Transcribed from `Website\WebsitePostResource` and
 * `Website\WebsiteReplyResource` — the two resources `PostController` and
 * `ReplyController` answer with. The `Community\PostResource` /
 * `Community\ReplyResource` pair is the admin shape and is not read here.
 *
 * Three properties of these payloads the types below encode:
 *
 * - **`replies` is detail-only.** `WebsitePostResource` takes a `$detail` flag
 *   and only then eager-loads and emits `replies`. `index()` does not pass it,
 *   `show()` does — so `CommunityPostRecord` has no replies and
 *   `CommunityPostDetailRecord` adds them.
 * - **A reply nests its own replies, recursively.** `child_replies` is always
 *   present (`[]` when there are none) and each element is another reply with
 *   its own `child_replies`, resolved lazily by `loadMissing('children')`.
 * - **`tags[]` carries a single `name`**, not the `name_en` / `name_ar` pair
 *   every other tag-shaped payload in this API uses. It is the
 *   `community_tags` table, not `master_choices`.
 */

import type { WebsiteChoiceDisplay } from "@/features/shared/apiPrimitives";

/**
 * The author block on a post or reply: `BuildsWebsiteFields::postUserPayload()`.
 *
 * Returns `null` when the row has no user. `full_name` comes from `fullName()`,
 * which returns `''` rather than null when there is no name to show, and falls
 * back to the organisation's name for an organisation account.
 */
export interface CommunityUserRecord {
  id: number;
  full_name: string;
  /** `profilePicUrl()` — the upload, else the social avatar, else null. */
  profile_pic: string | null;
  gender_display: WebsiteChoiceDisplay | null;
  /** Defaults to `false` when the account has no volunteer profile. */
  is_public: boolean;
  user_type: string | null;
}

/** One uploaded image on a post or reply. `getimg()` returns null for an empty column. */
export interface CommunityImageRecord {
  id: number;
  image: string | null;
}

/**
 * One community tag.
 *
 * A single `name` — these are `community_tags` rows, which are not localized,
 * unlike the `master_choices` interests used everywhere else.
 */
export interface CommunityTagRecord {
  id: number;
  name: string | null;
}

/** Counts and flags shared by a post and a reply. */
interface CommunityEngagement {
  /** Counted server-side across all users, so it is never locale-formatted. */
  likes_count: number;
  /** **`false` for an anonymous reader**, not null — the resource short-circuits. */
  is_liked: boolean;
  /** Likewise `false` when nobody is signed in, so it never means "unknown". */
  is_creator: boolean;
}

/** `WebsiteReplyResource` — a community reply, and its nested replies. */
export interface CommunityReplyRecord extends CommunityEngagement {
  id: number;
  post_id: number;
  /** Null for a top-level reply; the parent reply's id for a nested one. */
  parent_id: number | null;
  text_en: string | null;
  text_ar: string | null;
  /** The volunteer's chosen nickname, or the organisation's. Null for neither. */
  nickname: string | null;
  user: CommunityUserRecord | null;
  reply_images: CommunityImageRecord[];
  /** Always present — `[]` when there are none. Recursive. */
  child_replies: CommunityReplyRecord[];
  created_at: string | null;
}

/** `WebsitePostResource` without `detail` — the list row. */
export interface CommunityPostRecord extends CommunityEngagement {
  id: number;
  title_en: string | null;
  title_ar: string | null;
  idea_text_en: string | null;
  idea_text_ar: string | null;
  nickname: string | null;
  proposing_idea: boolean;
  is_funding_required: boolean;
  /** Top-level replies only — nested ones are not counted. */
  replies_count: number;
  user: CommunityUserRecord | null;
  post_images: CommunityImageRecord[];
  tags: CommunityTagRecord[];
  created_at: string | null;
}

/**
 * `WebsitePostResource` built with `detail: true` — `GET /posts/{id}/`.
 *
 * `replies` holds the **top-level** replies only (the eager load filters
 * `whereNull('parent_id')`); each one carries its own `child_replies`.
 */
export interface CommunityPostDetailRecord extends CommunityPostRecord {
  replies: CommunityReplyRecord[];
}

/**
 * A reply as the **UI** holds it: the payload, plus the three fields the
 * screens read that no resource emits.
 *
 * - `isPlaceholder` is a client-only optimistic row, added by the reply forms
 *   before the server answers.
 * - **`is_deleted` and `parent_is_deleted` are not in the payload.**
 *   `WebsiteReplyResource` emits neither, and five components read
 *   `!reply.is_deleted`. That is a benign no-op rather than a bug: every reply
 *   endpoint already scopes its query with `notDeleted()`, so a deleted reply
 *   never reaches the client and `!undefined` correctly keeps every row. They
 *   are typed optional here so the reads keep compiling and the reason they
 *   always pass is written down — two local `Reply` interfaces declared them
 *   **required**, which read as a guarantee the API makes and does not.
 */
export interface CommunityReplyView extends Omit<CommunityReplyRecord, "user"> {
  /**
   * Narrowed to non-null, unlike the record it extends.
   *
   * `postUserPayload()` is typed `?array` and returns null for a reply with no
   * author, but `replies.user_id` is `foreignId()->constrained()
   * ->cascadeOnDelete()` — NOT NULL, and deleting the user deletes the reply —
   * and `Reply::user()` is an unscoped `belongsTo`, so it resolves even for a
   * soft-deleted account. The null branch is therefore unreachable short of a
   * broken foreign key, and twenty reads across five components rely on that.
   * The record type stays honest about the resource; this is the invariant the
   * schema actually gives.
   */
  user: CommunityUserRecord;
  child_replies: CommunityReplyView[];
  /** Client-only: an optimistic row awaiting the server's answer. */
  isPlaceholder?: boolean;
  /** Never sent — see the note above. */
  is_deleted?: boolean;
  /** Never sent — see the note above. */
  parent_is_deleted?: boolean;
}

/**
 * A post or reply id as the community screens receive it.
 *
 * `number | string` because both really happen, and the two sources meet in
 * the same props:
 *
 * - the **payload** gives a number (`$post->id`, `$reply->id`);
 * - a **route param** gives a string (`/community/[postId]/reply/[replyId]`).
 *
 * `CommunityDetailPage` passes `postData.id` into the very prop
 * `ReplyDetailPage` fills from `useParams`. Those props declared `string`,
 * which made the numeric half a silent lie — `String(postId)` was already
 * being written at the call sites that needed a real string (see
 * `useUserReply`), which is the shape of a contract that was never true.
 *
 * Anything that compares one of these must coerce; anything that interpolates
 * it into a URL or a form field can use it as-is.
 */
export type CommunityEntityId = number | string;

/**
 * The payload → view boundary for replies.
 *
 * `CommunityReplyView` narrows `user` to non-null (see its note), so the
 * conversion has to be explicit rather than an assertion. A row with no author
 * is **dropped**, recursively, rather than rendered: the alternative is a
 * reply card with no name and no avatar whose "is this mine?" check cannot be
 * evaluated. The schema says this cannot happen — `replies.user_id` is a NOT
 * NULL cascade FK — so in practice nothing is ever dropped; this is the one
 * place that assumption is written down and enforced instead of being spread
 * across twenty optional-chained reads.
 */
export function asReplyViews(
  replies: readonly CommunityReplyRecord[] | null | undefined
): CommunityReplyView[] {
  const views: CommunityReplyView[] = [];
  for (const reply of replies ?? []) {
    if (!reply.user) continue;
    views.push({
      ...reply,
      user: reply.user,
      child_replies: asReplyViews(reply.child_replies),
    });
  }
  return views;
}

/** One `@handle` that resolved to a real account. */
export interface CommunityMentionRecord {
  id: number;
  /** `users.username` — nullable in the column, so nullable here. */
  username: string | null;
}

/**
 * What `PATCH /replies/{id}/` answers with: the reply as the list carries it,
 * plus the mentions found in the text it was just given.
 *
 * `mentioned_users` is spliced on by `ReplyController::update()` rather than by
 * the resource, so it appears on this one endpoint and nowhere the reply is
 * merely read. It was typed `unknown`, which left the only key that
 * distinguishes this reply from any other unreadable.
 */
export interface UpdatedCommunityReplyRecord extends CommunityReplyRecord {
  mentioned_users: CommunityMentionRecord[];
}
