import Mirage from 'ember-cli-mirage';
import { assign } from 'ember-platform';

export const BASE_URL = 'http://api.twitch.tv/v5';

export default function (server, namespace = BASE_URL) {
  server.namespace = namespace;

  server.post('/channels/:channelId/events', function({ events, channels, games }, { requestBody, params }) {
    let payload = JSON.parse(requestBody);
    let channel = channels.where({ _id: params.channelId }).models[0];

    let game;
    if (payload.game_id) {
      game = games.where({ _id: payload.game_id }).models[0];
    }

    return events.create(assign({}, payload, { channel, game }));
  });

  server.get('/channels/:channelId/events', function(schema, request) {
    let _id = request.params.channelId;
    let channel = schema.channels.where({ _id }).models[0];
    let events = channel.events;

    return events ? events : new Mirage.Response(404, {}, { status: 404, error: `no events for channel '${ _id }'` });
  });

  server.put('/events/:eventId', function(schema, { requestBody, params }) {
    let id = params.eventId;
    let event = schema.events.find(id);

    if (!event) {
      return new Mirage.Response(404, {}, {
        status: 404,
        error: `no event found with id ${ id }`
      });
    }

    let payload = JSON.parse(requestBody);
    event.update(payload);

    return event.reload();
  });

  server.delete('/events/:eventId', function(schema, request) {
    let eventId = request.params.eventId;
    schema.db.events.remove(eventId);

    return new Mirage.Response(204);
  });

  server.namespace = undefined;
}
