{"size": 2082, "ext": "js", "max_stars_repo_path": "edge/handlers/_conns/twilio/index.js", "max_stars_repo_name": "murielsilveira/atreyu", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "edge/handlers/_conns/twilio/index.js", "max_issues_repo_name": "murielsilveira/atreyu", "max_issues_repo_issues_event_min_datetime": "2021-09-30T11:24:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T12:09:30.000Z", "max_forks_repo_path": "edge/handlers/_conns/twilio/index.js", "max_forks_repo_name": "murielsilveira/atreyu", "max_forks_repo_forks_event_min_datetime": "2021-09-29T15:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T15:32:45.000Z"}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": 1, "avg_line_length": 28.5205479452, "max_line_length": 109, "alphanum_fraction": 0.6066282421}
/* global Response, IVR_PASSWORD, IVR_USER, IVR_SECRET  */
import { create } from '../../../inbox/helpers'
import callIn from './call_in'
import smsOut from './sms_out'
import callUpdt from './call_updt'

export default function ({ req, finish, parsedBody, event, stats }) {
  if (parsedBody.password) {
    if (parsedBody.password !== IVR_PASSWORD || parsedBody.username !== IVR_USER) {
      return finish(new Response(JSON.stringify({error: 'invalid_request'}),
        {
          status: 401,
          statusText: 'Unauthorized',
          headers: {
            'content-type': 'application/json'
          }
        }), parsedBody)
    }

    return finish(new Response(JSON.stringify({
      access_token: IVR_SECRET,
      expires_in: 1540000000
    }), {
      status: 200,
      statusText: 'OK',
      headers: {
        'content-type': 'application/json'
      }
    }), parsedBody)
  }

  if (req.headers['authorization'] !== `Bearer ${IVR_SECRET}`) {
    return finish(new Response(JSON.stringify({error: 'invalid_request'}),
      {
        status: 401,
        statusText: 'Unauthorized',
        headers: {
          'content-type': 'application/json'
        }
      }), parsedBody)
  }

  const tel = parsedBody.device.mdn
  const ivrEvent = parsedBody.event

  let doc
  if (ivrEvent.properties.call_type.toLocaleLowerCase() !== 'mobile') {
    return finish(new Response('OK', {
      status: 200,
      statusText: 'OK',
      headers: {}
    }), parsedBody)
  } else if (ivrEvent.name === 'call_received' || ivrEvent.name === 'call_started') {
    doc = callIn({tel, ivrEvent, stats})
  } else if (ivrEvent.name === 'conversation_initiated' || ivrEvent.name === 'busy_conversation_initiated') {
    doc = smsOut({tel, ivrEvent, stats})
  } else {
    event.waitUntil(callUpdt({tel, ivrEvent, stats}))

    return finish(new Response('OK', {
      status: 200,
      statusText: 'OK',
      headers: {}
    }), parsedBody)
  }

  return finish(create({
    doc,
    userId: 'connectors',
    dbUrl: 'https://couch.cloudless.one/user_jan'
  }), parsedBody)
}
