export function getObjectIdParamName(modelName) {
  return `${modelName}Id`
}

export function getObjectIdFromSearch(modelName, search) {
  const params = new URLSearchParams(search)
  return params.get(getObjectIdParamName(modelName))
}

export function getModelRoutePath(model) {
  return model.url.replace(/^\/dashboard\//, '')
}

export function buildActionUrl(model, action, objectId, pathname, search = '') {
  if (typeof action.url === 'function') {
    return action.url(objectId)
  }

  const idParam = getObjectIdParamName(model.name)
  const pageName = action.pageName || action.name

  if (action.type === 'page') {
    const params = new URLSearchParams()
    params.set(idParam, objectId)
    if (action.name !== pageName) {
      params.set('action', action.name)
    }
    return `/dashboard/${getModelRoutePath(model)}/${pageName}?${params.toString()}`
  }

  const params = new URLSearchParams(search)
  params.set('action', action.name)
  params.set('actionObjectType', model.name)
  const query = params.toString()
  return `${pathname}${query ? `?${query}` : ''}`
}

export function stripPageActionParams(pathname, search) {
  const params = new URLSearchParams(search)
  params.delete('action')
  const query = params.toString()
  return pathname + (query ? `?${query}` : '')
}

export function stripModalActionParams(pathname, search) {
  const params = new URLSearchParams(search)
  params.delete('action')
  params.delete('actionObjectType')
  const query = params.toString()
  return pathname + (query ? `?${query}` : '')
}

export function stripActionParams(pathname, search) {
  return stripPageActionParams(pathname, search)
}

export function findAction(model, actionName) {
  const findInActions = (actions) => {
    if (!Array.isArray(actions)) return null
    for (const action of actions) {
      if (action.type === 'divider') continue
      if ((action.key || action.name) === actionName) return action
      if (action.children) {
        const found = findInActions(action.children)
        if (found) return found
      }
    }
    return null
  }
  return findInActions(model?.actions)
}
