/**
 * The reply payload → view conversion.
 *
 * `WebsiteReplyResource` types its author block `?array`, while every reply
 * card reads `reply.user.full_name` and friends unconditionally. These pin
 * which of the two wins and what happens to a row that cannot satisfy it.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { asReplyViews } from "@/features/community/communityRecord";
import type {
  CommunityReplyRecord,
  CommunityUserRecord,
} from "@/features/community/communityRecord";

const user: CommunityUserRecord = {
  id: 3,
  full_name: "Noor",
  profile_pic: null,
  gender_display: null,
  is_public: false,
  user_type: "volunteer",
};

const reply = (over: Partial<CommunityReplyRecord> = {}): CommunityReplyRecord => ({
  id: 1,
  post_id: 10,
  parent_id: null,
  text_en: "hello",
  text_ar: null,
  nickname: null,
  is_creator: false,
  likes_count: 0,
  is_liked: false,
  user,
  reply_images: [],
  child_replies: [],
  created_at: null,
  ...over,
});

describe("asReplyViews", () => {
  test("null and undefined give an empty list", () => {
    assert.deepEqual(asReplyViews(null), []);
    assert.deepEqual(asReplyViews(undefined), []);
  });

  test("a reply with an author is carried through", () => {
    const [view] = asReplyViews([reply()]);
    assert.equal(view.user.full_name, "Noor");
    assert.equal(view.post_id, 10);
  });

  test("a reply with no author is dropped, not rendered nameless", () => {
    assert.deepEqual(asReplyViews([reply({ user: null })]), []);
  });

  test("the drop is recursive — a nested authorless reply goes too", () => {
    const [view] = asReplyViews([
      reply({
        id: 1,
        child_replies: [reply({ id: 2, user: null }), reply({ id: 3 })],
      }),
    ]);
    assert.deepEqual(view.child_replies.map((c) => c.id), [3]);
  });

  test("nesting deeper than one level is converted too", () => {
    const [view] = asReplyViews([
      reply({ id: 1, child_replies: [reply({ id: 2, child_replies: [reply({ id: 4 })] })] }),
    ]);
    assert.equal(view.child_replies[0].child_replies[0].id, 4);
  });

  test("order is preserved", () => {
    const views = asReplyViews([reply({ id: 9 }), reply({ id: 2 }), reply({ id: 5 })]);
    assert.deepEqual(views.map((v) => v.id), [9, 2, 5]);
  });

  test("the client-only flags are absent until a screen sets them", () => {
    // `isSaved`-style additions: not in the payload, so not invented here.
    const [view] = asReplyViews([reply()]);
    assert.equal(view.isPlaceholder, undefined);
    assert.equal(view.is_deleted, undefined);
  });
});
