import { ChatRoom, fetchChatRooms } from '@/lib/api';

const ACTIVE_ROOM_STORAGE_PREFIX = 'lendry-family-active-room:';

export function readStoredActiveRoomId(groupId: string) {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem(`${ACTIVE_ROOM_STORAGE_PREFIX}${groupId}`);
}

export function storeActiveRoomId(groupId: string, roomId: string | null) {
  if (typeof window === 'undefined') return;
  const key = `${ACTIVE_ROOM_STORAGE_PREFIX}${groupId}`;
  if (!roomId) {
    localStorage.removeItem(key);
    return;
  }
  localStorage.setItem(key, roomId);
}

export function findMemberRoom(
  rooms: ChatRoom[],
  memberUserId: string,
  currentUserId: string,
  options?: { isBot?: boolean; e2e?: boolean }
) {
  const targetType = options?.isBot ? 'BOT' : options?.e2e ? 'E2E' : 'DIRECT';
  return rooms.find(
    (room) =>
      room.type === targetType &&
      room.members.some((member) => member.userId === memberUserId) &&
      room.members.some((member) => member.userId === currentUserId)
  );
}

export async function findOrCreateMemberChat(
  groupId: string,
  memberUserId: string,
  _memberName: string,
  currentUserId: string,
  token: string
) {
  const response = await fetchChatRooms(groupId, token);
  const rooms = response.rooms ?? [];
  const member = rooms.find(
    (room) =>
      (room.type === 'DIRECT' || room.type === 'BOT') &&
      room.members.some((item) => item.userId === memberUserId) &&
      room.members.some((item) => item.userId === currentUserId)
  );
  if (member) return member;
  throw new Error('Чат ещё не создан. Обновите страницу семьи.');
}

export function roomDisplayLabel(room: ChatRoom, currentUserId: string) {
  if (room.type === 'GENERAL') return room.name;
  if (room.type === 'BOT') return room.name;
  if (room.type === 'E2E') {
    const other = room.members.find((member) => member.userId !== currentUserId);
    return other ? `🔒 ${other.displayName}` : '🔒 Секретный чат';
  }
  if (room.type === 'DIRECT' || room.members.length === 2) {
    const other = room.members.find((member) => member.userId !== currentUserId);
    if (other) return other.displayName;
  }
  return room.name;
}
