import { Event } from 'nostr-tools'
import { SignedEvent } from '../types'
import { saveAuthToken } from './localStorage'

export const base64EncodeSignedEvent = (event: SignedEvent) => {
  try {
    const authEventSerialized = JSON.stringify(event)
    const token = btoa(authEventSerialized)
    return token
  } catch (error) {
    throw new Error('An error occurred in JSON.stringify of signedAuthEvent')
  }
}

export const base64DecodeAuthToken = (authToken: string): SignedEvent => {
  const decodedToken = atob(authToken)

  try {
    const signedEvent = JSON.parse(decodedToken)
    return signedEvent
  } catch (error) {
    throw new Error('An error occurred in JSON.parse of the auth token')
  }
}

export const createAndSaveAuthToken = (signedAuthEvent: SignedEvent) => {
  const base64Encoded = base64EncodeSignedEvent(signedAuthEvent)

  // save newly created auth token (base64 nostr signed event) in local storage along with expiry time
  saveAuthToken(base64Encoded)
  return base64Encoded
}

export const getEmptyMetadataEvent = (pubkey?: string): Event => {
  return {
    content: '',
    created_at: new Date().valueOf(),
    id: '',
    kind: 0,
    pubkey: pubkey || '',
    sig: '',
    tags: []
  }
}
