"use strict";

import { getChatsPrivateStoreRequest } from './getChatsPrivateStoreRequest.xmpp';
import { setChatsPrivateStoreRequest } from './setChatsPrivateStoreRequest.xmpp';
/**
 * Merge in-memory lastViewedTimestamp values into the server-side
 * private store. Reads current state, overlays per-room updates, writes
 * back. Single round-trip so concurrent open clients don't trample
 * each other's entries.
 *
 * Called on: tab change away from chat, AppState background/inactive,
 * and (with onlyIfNoUnread=true) logout. ChatRoom's own unmount path
 * still uses actionSetTimestampToPrivateStore for the single-room case.
 */
export async function flushLastViewedToPrivateStore(client, rooms, opts = {}) {
  if (!client?.client) {
    return false;
  }
  const {
    visibleRoomJID,
    onlyIfNoUnread
  } = opts;
  const roomList = Object.values(rooms || {});
  if (roomList.length === 0) {
    return false;
  }
  let storeObj = null;
  try {
    storeObj = await getChatsPrivateStoreRequest(client.client);
  } catch {
    storeObj = null;
  }
  if (!storeObj || typeof storeObj !== 'object') {
    storeObj = {};
  }
  const nowMs = Date.now();
  let dirty = false;
  for (const room of roomList) {
    if (!room?.jid) {
      continue;
    }
    const isVisible = !!visibleRoomJID && room.jid === visibleRoomJID;
    const hasUnread = Number(room.unreadMessages || 0) > 0;

    // For the visible room, persist "now" — read state is driven by
    // room visibility, not by a sentinel timestamp.
    let ts;
    if (isVisible) {
      ts = nowMs;
    } else if (room.lastViewedTimestamp && room.lastViewedTimestamp > 0) {
      ts = room.lastViewedTimestamp;
    }
    if (!ts) {
      continue;
    }
    if (onlyIfNoUnread && hasUnread && !isVisible) {
      continue;
    }
    const prev = storeObj[room.jid];
    const prevNum = prev != null ? Number(prev) : 0;
    if (Number.isFinite(prevNum) && prevNum >= ts) {
      continue;
    }
    storeObj[room.jid] = String(ts);
    dirty = true;
  }
  if (!dirty) {
    return false;
  }
  try {
    await setChatsPrivateStoreRequest(client.client, JSON.stringify(storeObj));
    return true;
  } catch {
    return false;
  }
}
//# sourceMappingURL=flushLastViewedToPrivateStore.js.map