export function sortSessions(records) {
    return [...records].sort((a, b) => (b.updatedAt - a.updatedAt) || a.id.localeCompare(b.id));
}
export function sortMessages(records) {
    return [...records].sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
}
export function sortInputs(records) {
    return [...records].sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
}
export function loadSessionBrokerState(snapshot) {
    const sessions = new Map();
    const messages = new Map();
    const inputs = new Map();
    for (const session of snapshot?.sessions ?? []) {
        sessions.set(session.id, session);
    }
    for (const message of snapshot?.messages ?? []) {
        const bucket = messages.get(message.sessionId) ?? [];
        bucket.push(message);
        messages.set(message.sessionId, bucket);
    }
    for (const input of snapshot?.inputs ?? []) {
        const bucket = inputs.get(input.sessionId) ?? [];
        bucket.push(input);
        inputs.set(input.sessionId, bucket);
    }
    for (const [sessionId, bucket] of messages.entries()) {
        messages.set(sessionId, sortMessages(bucket));
    }
    for (const [sessionId, bucket] of inputs.entries()) {
        inputs.set(sessionId, sortInputs(bucket));
    }
    return { sessions, messages, inputs };
}
export function createSessionBrokerSnapshot(state, maxPersistedMessages) {
    const messages = [...state.messages.values()].flatMap((bucket) => bucket);
    const inputs = [...state.inputs.values()].flatMap((bucket) => bucket);
    return {
        sessions: sortSessions(state.sessions.values()),
        messages: sortMessages(messages).slice(-maxPersistedMessages),
        inputs: sortInputs(inputs),
    };
}
export function upsertSessionParticipant(participants, participant) {
    const participantId = buildSessionParticipantId(participant);
    return [
        ...participants.filter((existing) => buildSessionParticipantId(existing) !== participantId),
        participant,
    ];
}
export function countPendingSessionInputs(records) {
    return records.filter((entry) => entry.state === 'queued' || entry.state === 'delivered' || entry.state === 'spawned').length;
}
function buildSessionParticipantId(participant) {
    return `${participant.surfaceKind}:${participant.surfaceId}:${participant.externalId ?? ''}:${participant.userId ?? ''}`;
}
