import { getContextPath, getRepository } from '@things-factory/shell'

import { Process } from '../service/process/process'

export const headlessModel = async target => {
  var { domain, id, model } = target || {}

  if (model) {
    if (typeof model == 'string') {
      model = JSON.parse(model)
    } else if (typeof model !== 'object') {
      throw 'model should be a string or object'
    }
  } else if (id) {
    const repository = getRepository(Process)
    var process = await repository.findOneBy({ domain: { id: domain.id }, id })
    model = JSON.parse(process.model)
  } else {
    throw 'parameter model or id mandatory'
  }

  return {
    base: getContextPath(domain?.subdomain),
    model,
    process
  }
}
