import * as sdk from '@botpress/sdk'
import { StoredCredentials } from './types'
import * as bp from '.botpress'

export const getStoredCredentials = async (client: bp.Client, ctx: bp.Context): Promise<StoredCredentials> => {
  const {
    state: { payload: credentials },
  } = await client.getOrSetState({
    name: 'credentials',
    type: 'integration',
    id: ctx.integrationId,
    payload: {},
  })

  const { token, appId, subdomain } = credentials

  if (!token || !appId) {
    throw new sdk.RuntimeError('Failed to get credentials, please authenticate first')
  }

  return { token, appId, subdomain }
}
