"use strict";

const { validateArguments } = require("@validatem/core");
const required = require("@validatem/required");
const concatArrays = require("concat-arrays");
const itemDeduplicator = require("../item-deduplicator");

const isMessagesResponse = require("../is-messages-response");

module.exports = function parseMessagesResponse(_response, strict = false) {
	// FIXME: Figure out a way to soft-fail, and turn the validation error into a warning event
	let [ response ] = validateArguments(arguments, {
		response: [ required, isMessagesResponse(strict) ]
	});

	let deduplicateEvent = itemDeduplicator((event) => event.event_id);

	function toTimestampedEvent(event, type) {
		return {
			type: type,
			event: deduplicateEvent(event),
			timestamp: event.origin_server_ts
		};
	}

	if (response.chunk.length > 0) {
		return {
			events: concatArrays(
				response.chunk.map((event) => toTimestampedEvent(event, "roomTimelineEvent")),
				response.state.map((event) => toTimestampedEvent(event, "roomStateUpdate")),
			),
			paginationToken: response.end
		};
	} else {
		return { events: [] };
	}
};
