import { readFile } from 'fs/promises'

import { initScenid, sdk } from '@scenid/cloud-sdk'

// Loads the service key given as first CLI argument (or SCENID_SERVICE_KEY) and initialises the SDK.
export const connect = async () => {
  const path = process.argv[2] ?? process.env.SCENID_SERVICE_KEY
  if (!path) {
    console.error('Usage: node <script>.mjs <path-to-service-key.json>')
    process.exit(1)
  }

  initScenid(JSON.parse(await readFile(path, 'utf8')))
  return sdk
}

// The SDK does not throw on HTTP errors, it resolves { status, result }. This helper throws instead.
export const expectOk = ({ status, result }, label) => {
  if (status >= 200 && status < 300) return result
  throw new Error(`${label} failed with ${status}: ${JSON.stringify(result)}`)
}
