import { Wallet } from 'ethers'

const API_URL: string = 'https://tools.le7el.com/tools/v1/events'

export default class Le7eLEvents {
  private readonly api_url: string
  private readonly signer: Wallet

  constructor(private_key: string, api_url: string = API_URL) {
    this.signer = new Wallet(private_key)
    this.api_url = api_url
  }

  public sendEvent(
    user_id: string,
    event: string,
    payload: Object,
    nonce: number = 0,
    context_type: string = 'filter',
    user_id_type: string = 'wallet',
    platform: string = 'web'
  ) {
    if (context_type !== 'filter') throw 'only fitlers are supported as context'
    if (user_id_type !== 'wallet') throw 'only wallets are supported as user id type'
    if (!user_id) throw 'user is required'
    if (!event) throw 'event is required'
    if (!nonce || nonce == 0) nonce = Date.now()

    const data: string = JSON.stringify({
      nonce,
      user_id,
      user_id_type,
      context_type,
      platform,
      event,
      payload
    })

    const api_url: string = this.api_url

    return this.signer.signMessage(data)
      .then((raw_signature: string) => {
        return fetch(api_url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${raw_signature}`,
            "Nonce": `${nonce}`
          },
          body: data
        })
      })
      .then((response: Response) => response.json())
      .then((data: any) => console.log(data))
  }
}