import Mirage from 'ember-cli-mirage';

export default function(server, namespace = 'http://im.twitch.tv/v1') {
  server.namespace = namespace;

  server.get('/unread', function(schema) {
    let unreads = schema.db.unreads;
    return {
      complete: true,
      unread_messages: unreads.length,
      data: unreads
    };
  });

  server.get('/threads', function(schema) {
    let threads = schema.db.threads;
    return {
      total: threads.length,
      data: threads
    };
  });

  function findByIdPair(table, id) {
    let reverseId = id.split('_').reverse().join('_');
    return table.where({ id})[0] || table.where({ id: reverseId })[0];
  }

  server.get('/threads/:id', function(schema, request) {
    let id = request.params.id;
    let thread = findByIdPair(schema.db.threads, id);
    if (thread) {
      return thread;
    }

    return new Mirage.Response(404, {}, { status: 404, error: 'not found' });
  });

  server.post('/threads/:id', function(schema, request) {
    // web-client sends a request here to mark threads as read when opened.
    let id = request.params.id;
    let body = JSON.parse(request.requestBody);
    if (body.mark_read) {
      let unread = findByIdPair(schema.db.unreads, id);
      schema.db.unreads.update(unread, { last_read_message_id: body.mark_read });
    }

    let thread = findByIdPair(schema.db.threads, id);
    return thread;
  });

  server.get('/threads/:id/messages', function(schema, request) {
    let id = request.params.id;
    let thread = findByIdPair(schema.db.threads, id);
    let lastMessage = thread.last_message;
    return {
      data: [ lastMessage ]
    };
  });

  server.post('/messages', function(schema, request) {
    let body = JSON.parse(request.requestBody);
    let message = schema.messages.create(body);
    return {
      authorized: true,
      message_id: message.id
    };
  }, 200);

  server.namespace = undefined;
}
