import { describe, expect, it } from "@jest/globals";
import { getMessageAuthorDisplay } from "./messageAuthor";

describe("getMessageAuthorDisplay", () => {
  it("prefers channel member data for another participant", () => {
    const display = getMessageAuthorDisplay({
      userId: "member-1",
      members: {
        "member-1": {
          id: "member-1",
          name: "Alice Martin",
          avatar_url: "https://assets.xtablo.com/alice.jpg",
        },
      },
      currentUser: {
        id: "me",
        name: "Me",
        avatar_url: "https://assets.xtablo.com/me.jpg",
      },
      failedAvatarUserIds: {},
    });

    expect(display).toEqual({
      name: "Alice Martin",
      avatarUrl: "https://assets.xtablo.com/alice.jpg",
      initial: "A",
    });
  });

  it("falls back to the current user when the current member is not in the channel map", () => {
    const display = getMessageAuthorDisplay({
      userId: "me",
      members: {},
      currentUser: {
        id: "me",
        name: "Bob Owner",
        avatar_url: "https://assets.xtablo.com/bob.jpg",
      },
      failedAvatarUserIds: {},
    });

    expect(display).toEqual({
      name: "Bob Owner",
      avatarUrl: "https://assets.xtablo.com/bob.jpg",
      initial: "B",
    });
  });

  it("suppresses the avatar URL after an image failure has been recorded", () => {
    const display = getMessageAuthorDisplay({
      userId: "member-1",
      members: {
        "member-1": {
          id: "member-1",
          name: "Alice Martin",
          avatar_url: "https://assets.xtablo.com/alice.jpg",
        },
      },
      currentUser: null,
      failedAvatarUserIds: {
        "member-1": true,
      },
    });

    expect(display).toEqual({
      name: "Alice Martin",
      avatarUrl: null,
      initial: "A",
    });
  });

  it("uses safe fallbacks when sender data is incomplete", () => {
    const display = getMessageAuthorDisplay({
      userId: "missing",
      members: {},
      currentUser: null,
      failedAvatarUserIds: {},
    });

    expect(display).toEqual({
      name: "Utilisateur",
      avatarUrl: null,
      initial: "U",
    });
  });
});
