import { EventInput } from './dto/shared.dto'

if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer

const DEFAULT_METRICS_URL = 'https://affinity-metrics.dev.affinity-project.org'

let fetch: any

if (!fetch) {
  fetch = require('node-fetch')
}

const keccak256 = require('keccak256')

class Metrics {
  _prepareEventParams(event: EventInput) {
    const { link } = event
    const linkBuffer = Buffer.from(link)
    const hashedLinkBuffer = keccak256(linkBuffer)

    return Object.assign({}, event, { link: hashedLinkBuffer.toString('hex') })
  }

  async send(eventInput: EventInput, apiKey: string, metricsUrl?: string): Promise<any> {
    const event = this._prepareEventParams(eventInput)

    metricsUrl = metricsUrl || DEFAULT_METRICS_URL
    const url  = `${metricsUrl}/api/v1/events/createEvent`
    const body = JSON.stringify(event, null, 2)

    const headers  = {
      Accept:         'application/json',
      'Content-Type': 'application/json',
      'Api-Key':       apiKey
    }

    const response = await fetch(url, { method: 'POST', headers, body })
    const result   = await response.json()

    if (response.status.toString().startsWith('2')) {
      return result
    } else {
      throw new Error(result)
    }
  }
}

export const metrics = new Metrics()
