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

import { Process } from '../../service/process/process'
import { ProcessHistory } from '../../service/process/process-history'

export const headlessModel = async (target, draft: boolean = false) => {
  var { domain, id, model, name } = 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) {
      var process = await getRepository(Process).findOne({
        where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, id }
      })
    } else if (name) {
      var process = await getRepository(Process).findOne({
        where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean)) }, name }
      })
    } else {
      throw 'parameter model or id mandatory'
    }

    if (!draft && process) {
      const latestReleased =
        process.state == 'released'
          ? process
          : await getRepository(ProcessHistory)
              .createQueryBuilder('history')
              .where('history.originalId = :originalId', { originalId: process.id })
              .orderBy('history.version', 'DESC')
              .limit(1)
              .getOne()

      model = (latestReleased || process).model
    } else {
      model = process.model
    }

    model = JSON.parse(model)
  }

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