import later from 'later'
import createQueue from 'bull'
import url from 'url'

import {serverToServerJWT, graphQLFetcher} from '../util'

if (process.env.NODE_ENV === 'development') {
  require('dotenv').load()
}

const redisConfig = url.parse(process.env.REDIS_URL)
/* eslint-disable camelcase */
const redisOpts = redisConfig.auth ? {auth_pass: redisConfig.auth.split(':')[1]} : undefined
const syncPlayersWithIDM = createQueue('syncPlayersWithIDM', redisConfig.port, redisConfig.hostname, redisOpts)
const syncPlayersWithIDMSched = later.parse.recur().every(1).minute()
later.setInterval(() => {
  syncPlayersWithIDM.add({}, {attempts: 1})
}, syncPlayersWithIDMSched)

function processUsers(users) {
  // TODO: add users with role 'player' to database and associate them with the chapter whose inviteCode matches
  console.log('recent users:', users)
}

syncPlayersWithIDM.process((/* job */) => {
  const since = new Date(0).toISOString() // TODO: get this from our DB
  const graphQLParams = {
    query: `
query ($since: DateTime!) {
  getUsersCreatedSince(since: $since) {
    id
    inviteCode
    email
    handle
    createdAt
  }
}
    `,
    variables: {
      since,
    },
  }
  graphQLFetcher(serverToServerJWT(), process.env.IDM_BASE_URL)(graphQLParams)
    .then(resp => resp.json())
    .then(graphQLResponse => {
      if (graphQLResponse.errors && graphQLResponse.errors.length) {
        // throw the first error
        throw new Error(graphQLResponse.errors[0].message)
      }
      processUsers(graphQLResponse.data.getUsersCreatedSince)
    })
    .catch(error => {
      console.error(error.stack)
      throw error
    })
})

@@ -4,40 +4,15 @@
 ort 
-later from 'later'%0Aimport create
+getBull
 Queu
@@ -51,65 +51,66 @@
 rl'%0A
-%0A
 import 
-%7BserverToServerJWT, graphQLFetcher%7D from '../util
+raven from 'raven'%0A%0Aimport r from '../../db/connect
 '%0A%0Ai
@@ -184,16 +184,113 @@
 ad()%0A%7D%0A%0A
+const sentry = new raven.Client(process.env.SENTRY_SERVER_DSN)%0A%0Afunction getQueue(queueName) %7B%0A  
 const re
@@ -334,16 +334,18 @@
 IS_URL)%0A
+  
 /* eslin
@@ -367,16 +367,18 @@
 case */%0A
+  
 const re
@@ -466,67 +466,39 @@
 ned%0A
-const syncPlayersWithIDM = createQueue('syncPlayersWithIDM'
+  return getBullQueue(queueName
 , re
@@ -550,301 +550,185 @@
 ts)%0A
+%7D%0A%0A
 const 
-sync
+new
 Player
-sWithIDMSched = later.parse.recur().every(1).minute()%0Alater.setInterval(() =%3E %7B%0A  syncPlayersWithIDM.add(%7B%7D, %7Battempts: 1%7D)%0A%7D, syncPlayersWithIDMSched)%0A%0Afunction processUsers(users) %7B%0A  // TODO: add users wi
+ = getQueue('newPlayer')%0A%0AnewPlayer.process(async (%7Bdata: user%7D) =%3E %7B%0A  try %7B%0A    if (!user.inviteCode) %7B%0A      
 th
- 
 ro
-le 'player' to database and associate them with the chapter whose
+w new Error(%60user with id $%7Buser.id%7D has no
  inv
@@ -738,530 +738,310 @@
 Code
- matches%0A
+%60)%0A    %7D%0A 
   
+ 
 cons
-ole.log('recent users:', users)%0A%7D%0A%0AsyncPlayersWithIDM.process((/* job */) =%3E %7B%0A  const since = new Date(0).toISOString() // TODO: get this from our DB%0A  const graphQLParams = %7B%0A    query: %60%0Aquery ($since: DateTime!) %7B%0A  getUsersCreatedSince(since: $since) %7B%0A    id%0A    inviteCode%0A    email%0A    handle%0A    createdAt%0A  %7D%0A%7D%0A    %60,%0A    variables: %7B%0A      since,
+t chapters = await r.table('chapters').getAll(user.inviteCode, %7Bindex: 'inviteCodes'%7D).run()%0A    if (chapters.length === 0) %7B%0A      throw new Error(%60no chapter found for inviteCode $%7Buser.inviteCode%7D on user with id $%7Buser.id%7D%60)
 %0A    %7D
-,
 %0A  
-%7D%0A  graphQLFetcher(serverToServerJWT(), process.env.IDM_BASE_URL)(graphQLParams)%0A    .then(resp =%3E resp.json())%0A    .then(graphQLResponse
+  const chapter = chapters%5B0%5D%0A    const player
  =
-%3E
  %7B%0A 
@@ -1050,267 +1050,128 @@
    i
-f (graphQLResponse.errors && graphQLResponse.errors.length) %7B%0A        // throw the first error%0A        throw new Error(graphQLResponse.errors%5B0%5D.message)%0A      %7D%0A      processUsers(graphQLResponse.data.getUsersCreatedSince)%0A    %7D)%0A    .
+d: user.id,%0A      chapterId: chapter.id,%0A    %7D%0A    return r.table('players').insert(player).run()%0A  %7D 
 catch
+ 
 (err
-or =%3E
+)
  %7B%0A    
-  
 cons
@@ -1183,18 +1183,16 @@
 rror(err
-or
 .stack)%0A
@@ -1199,28 +1199,40 @@
     
-  throw error%0A    %7D)
+sentry.captureException(err)%0A  %7D
 %0A%7D)%0A

create new players (and associate with correct chapter) whenever one signs up in IDM service