import type { ChatMessage, SessionSnapshot } from "../../shared/types";
import { tStatic } from "../../i18n";

export type ChatThread = {
  id: string;
  name: string;
  kind: "global" | "group" | "direct";
  members: string[];
  lastMessage: ChatMessage | null;
};

function getLastMessage(messages: ChatMessage[]): ChatMessage | null {
  if (messages.length === 0) return null;
  return messages.reduce((latest, current) =>
    current.createdAt > latest.createdAt ? current : latest,
  );
}

export function buildThreads(
  session: SessionSnapshot,
  meId: string | null,
  isBanker: boolean,
): ChatThread[] {
  const threads: ChatThread[] = [];
  const globalMessages = session.chats.filter((message) => message.groupId === null);
  threads.push({
    id: "global",
    name: tStatic("chat.global"),
    kind: "global",
    members: [],
    lastMessage: getLastMessage(globalMessages),
  });

  session.groups.forEach((group) => {
    if (!isBanker && meId && !group.memberIds.includes(meId)) {
      return;
    }
    const groupMessages = session.chats.filter((message) => message.groupId === group.id);
    let name = group.name;
    let kind: ChatThread["kind"] = "group";
    if (group.memberIds.length === 2) {
      const [first, second] = group.memberIds;
      if (isBanker || !meId) {
        const firstName =
          session.players.find((player) => player.id === first)?.name ?? tStatic("common.player");
        const secondName =
          session.players.find((player) => player.id === second)?.name ?? tStatic("common.player");
        name = `${firstName} & ${secondName}`;
        kind = "direct";
      } else {
        const otherId = first === meId ? second : first;
        const otherName =
          session.players.find((player) => player.id === otherId)?.name ??
          tStatic("common.player");
        name = otherName;
        kind = "direct";
      }
    }
    threads.push({
      id: group.id,
      name,
      kind,
      members: group.memberIds,
      lastMessage: getLastMessage(groupMessages),
    });
  });

  return threads.sort((a, b) => {
    const aTime = a.lastMessage?.createdAt ?? 0;
    const bTime = b.lastMessage?.createdAt ?? 0;
    return bTime - aTime;
  });
}

export function getThreadMessages(session: SessionSnapshot, threadId: string): ChatMessage[] {
  if (threadId === "global") {
    return session.chats.filter((message) => message.groupId === null).slice().reverse();
  }
  return session.chats.filter((message) => message.groupId === threadId).slice().reverse();
}
