/* global window */
window.Niwa = window.Niwa || {};

window.Niwa.AdminChatHistory = (function () {
  'use strict';

  function create(opts) {
    opts = opts || {};
    var transport = opts.transport || null;
    var defaultLimit = parseInt(opts.defaultLimit || 30, 10) || 30;

    return {
      requestHistory: function (params) {
        return requestHistory(transport, defaultLimit, params);
      }
    };
  }

  function requestHistory(transport, defaultLimit, params) {
    if (!transport) return Promise.reject(new Error('missing_admin_chat_transport'));

    params = params || {};
    var fd = transport.baseFormData((window.NiwaAI && window.NiwaAI.history_action) || 'niwa_ai_admin_autonomy_history');
    fd.append('nonce', transport.getNonce());
    fd.append('mode', params.mode || 'initial');
    fd.append('limit', String(params.limit || defaultLimit || 30));
    if (params.before_ts) fd.append('before_ts', String(params.before_ts));
    if (params.since_ts) fd.append('since_ts', String(params.since_ts));
	if (params.before_id) fd.append('before_id', String(params.before_id));
	if (params.since_id) fd.append('since_id', String(params.since_id));

    return transport.fetchAjax(fd, false).then(function (response) {
      if (!response || !response.success || !response.data) {
        throw new Error('history_failed');
      }
      return {
        history: Array.isArray(response.data.history) ? response.data.history : [],
        hasMore: !!response.data.has_more,
        oldestTs: parseInt(response.data.oldest_ts || 0, 10) || 0,
		newestTs: parseInt(response.data.newest_ts || 0, 10) || 0,
		oldestId: response.data.oldest_id ? String(response.data.oldest_id) : '',
		newestId: response.data.newest_id ? String(response.data.newest_id) : ''
      };
    });
  }

  return {
    create: create
  };
})();
