Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

31.9 KB
Raw Blame
import {
  generateUniqueRefId,
  HoppCollection,
  HoppGQLRequest,
  HoppRESTRequest,
} from "@hoppscotch/data"

import {
  createRESTChildUserCollection,
  createRESTRootUserCollection,
  createRESTUserRequest,
  deleteUserCollection,
  deleteUserRequest,
  duplicateUserCollection,
  editUserRequest,
  importUserCollectionsFromJSON,
  moveUserCollection,
  moveUserRequest,
  sortUserCollections,
  updateUserCollection,
  updateUserCollectionOrder,
} from "./api"

import * as E from "fp-ts/Either"
import { ReqType, SortOptions } from "~/helpers/backend/graphql"
import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import {
  editGraphqlCollection,
  editGraphqlFolder,
  editRESTCollection,
  editRESTFolder,
  graphqlCollectionStore,
  navigateToFolderWithIndexPath,
  removeDuplicateRESTCollectionOrFolder,
  restCollectionStore,
} from "~/newstore/collections"
import { getSettingSubject, settingsStore } from "~/newstore/settings"
import {
  getSyncInitFunction,
  runDispatchWithOutSyncing,
  StoreSyncDefinitionOf,
} from ".."
import { createMapper } from "../mapper"

// restCollectionsMapper uses the collectionPath as the local identifier
// Helper function to transform HoppCollection to backend format
const transformCollectionForBackend = (collection: HoppCollection): any => {
  const data = {
    auth: collection.auth ?? {
      authType: "inherit",
      authActive: true,
    },
    headers: collection.headers ?? [],
    variables: stripClientLocalValuesForWire(collection.variables ?? []),
    _ref_id: collection._ref_id,
    description: collection.description ?? null,
    preRequestScript: collection.preRequestScript ?? "",
    testScript: collection.testScript ?? "",
  }

  return {
    name: collection.name,
    data: JSON.stringify(data),
    folders: collection.folders.map(transformCollectionForBackend),
    requests: collection.requests,
  }
}

export const restCollectionsMapper = createMapper<string, string>()

// restRequestsMapper uses the collectionPath/requestIndex as the local identifier
export const restRequestsMapper = createMapper<string, string>()

type ExportedCollectionFolder = {
  id?: string
  folders: ExportedCollectionFolder[]
  requests: Array<Record<string, unknown> & { id: string }>
  name: string
  data?: string
}

function findCollectionPathByID(
  collections: HoppCollection[],
  collectionID: string,
  currentPath: number[] = []
): number[] | undefined {
  for (const [index, collection] of collections.entries()) {
    const nextPath = [...currentPath, index]

    if (collection.id === collectionID) {
      return nextPath
    }

    const childPath = findCollectionPathByID(
      collection.folders ?? [],
      collectionID,
      nextPath
    )

    if (childPath) {
      return childPath
    }
  }

  return undefined
}

// Suffix stamped onto the optimistically-inserted duplicate in the
// `duplicateCollection` store dispatcher. Used here to locate that placeholder
// so it can be swapped for the backend response carrying the real IDs.
const DUPLICATE_COLLECTION_ID_SUFFIX = "-duplicate-collection"

// Find the index of the optimistically-inserted duplicate (its ID ends with
// DUPLICATE_COLLECTION_ID_SUFFIX) within a sibling list. The original is
// duplicated into its own parent, so the placeholder always sits alongside it.
function findDuplicatePlaceholderIndex(collections: HoppCollection[]): number {
  return collections.findIndex((collection) =>
    collection.id?.endsWith(DUPLICATE_COLLECTION_ID_SUFFIX)
  )
}

// Graft the backend-assigned IDs from the duplicate's exported representation
// onto the optimistically-inserted collection, matching folders/requests by
// position. Everything else the frontend already set (name, `_ref_id`, auth,
// headers, variables, scripts, etc.) is preserved — only the IDs change, so the
// placeholder `-duplicate-collection` IDs are replaced with the real ones the
// backend just created.
function applyExportedIdsToCollection(
  target: HoppCollection,
  exported: ExportedCollectionFolder
): HoppCollection {
  return {
    ...target,
    ...(exported.id ? { id: exported.id } : {}),
    folders: (target.folders ?? []).map((folder, index) => {
      const exportedFolder = exported.folders?.[index]
      return exportedFolder
        ? applyExportedIdsToCollection(folder, exportedFolder)
        : folder
    }),
    requests: (target.requests ?? []).map((request, index) => {
      const exportedRequest = exported.requests?.[index]
      return exportedRequest?.id
        ? { ...request, id: exportedRequest.id }
        : request
    }),
  }
}

export function applyDuplicatedCollectionResult(
  collectionType: "REST" | "GQL",
  originalCollectionID: string,
  exportedCollectionJSON: string
) {
  const parsed = JSON.parse(exportedCollectionJSON) as
    ExportedCollectionFolder | ExportedCollectionFolder[]

  // The backend may return either the duplicated collection directly or wrapped
  // in an array — normalize to the single duplicated collection.
  const duplicatedCollection = Array.isArray(parsed) ? parsed[0] : parsed
  if (!duplicatedCollection) return

  const { collectionStore } = getStoreByCollectionType(collectionType)
  const originalCollectionPath = findCollectionPathByID(
    collectionStore.value.state,
    originalCollectionID
  )

  if (!originalCollectionPath) return

  const parentCollectionPath = originalCollectionPath.slice(0, -1)

  runDispatchWithOutSyncing(() => {
    if (parentCollectionPath.length === 0) {
      // Locate the placeholder by its suffixed ID rather than assuming it's the
      // last root collection — otherwise a stale ID survives and subsequent
      // edits hit the backend with the bogus `-duplicate-collection` ID.
      const duplicateCollectionIndex = findDuplicatePlaceholderIndex(
        collectionStore.value.state
      )

      if (duplicateCollectionIndex === -1) return

      const placeholderCollection =
        collectionStore.value.state[duplicateCollectionIndex]

      const updatedCollection = applyExportedIdsToCollection(
        placeholderCollection,
        duplicatedCollection
      )

      if (collectionType === "REST") {
        editRESTCollection(duplicateCollectionIndex, updatedCollection)
      } else {
        editGraphqlCollection(duplicateCollectionIndex, updatedCollection)
      }

      return
    }

    const parentCollection = navigateToFolderWithIndexPath(
      collectionStore.value.state,
      parentCollectionPath
    )

    if (!parentCollection) return

    const duplicateCollectionIndex = findDuplicatePlaceholderIndex(
      parentCollection.folders
    )

    if (duplicateCollectionIndex === -1) return

    const placeholderCollection =
      parentCollection.folders[duplicateCollectionIndex]

    const updatedCollection = applyExportedIdsToCollection(
      placeholderCollection,
      duplicatedCollection
    )

    const duplicateCollectionPath = `${parentCollectionPath.join("/")}/${duplicateCollectionIndex}`

    if (collectionType === "REST") {
      editRESTFolder(duplicateCollectionPath, updatedCollection)
    } else {
      editGraphqlFolder(duplicateCollectionPath, updatedCollection)
    }
  })
}

// Optimized implementation using importUserCollectionsFromJSON for bulk operations
// This replaces individual createRESTRootUserCollection/createRESTChildUserCollection/createRESTUserRequest calls
const recursivelySyncCollections = async (
  collection: HoppCollection,
  collectionPath: string,
  parentUserCollectionID?: string
) => {
  let parentCollectionID = parentUserCollectionID

  // if parentUserCollectionID does not exist, create the collection as a root collection
  if (!parentUserCollectionID) {
    const data = {
      auth: collection.auth ?? {
        authType: "inherit",
        authActive: true,
      },
      headers: collection.headers ?? [],
      variables: stripClientLocalValuesForWire(collection.variables ?? []),
      _ref_id: collection._ref_id,
      description: collection.description ?? null,
      preRequestScript: collection.preRequestScript ?? "",
      testScript: collection.testScript ?? "",
    }
    const res = await createRESTRootUserCollection(
      collection.name,
      JSON.stringify(data)
    )
    if (E.isRight(res)) {
      parentCollectionID = res.right.createRESTRootUserCollection.id

      const returnedData = res.right.createRESTRootUserCollection.data
        ? JSON.parse(res.right.createRESTRootUserCollection.data)
        : {
            auth: {
              authType: "inherit",
              authActive: true,
            },
            headers: [],
            variables: [],
            _ref_id: generateUniqueRefId("coll"),
            description: null,
          }

      collection.id = parentCollectionID
      collection._ref_id = returnedData._ref_id ?? generateUniqueRefId("coll")
      collection.auth = returnedData.auth
      collection.headers = returnedData.headers
      collection.variables = returnedData.variables
      collection.description = returnedData.description ?? null
      removeDuplicateRESTCollectionOrFolder(
        parentCollectionID,
        `${collectionPath}`
      )
    } else {
      parentCollectionID = undefined
      return
    }
  } else {
    // if parentUserCollectionID exists, create the collection as a child collection
    const data = {
      auth: collection.auth ?? {
        authType: "inherit",
        authActive: true,
      },
      headers: collection.headers ?? [],
      variables: stripClientLocalValuesForWire(collection.variables ?? []),
      _ref_id: collection._ref_id,
      description: collection.description ?? null,
      preRequestScript: collection.preRequestScript ?? "",
      testScript: collection.testScript ?? "",
    }

    const res = await createRESTChildUserCollection(
      collection.name,
      parentUserCollectionID,
      JSON.stringify(data)
    )

    if (E.isRight(res)) {
      const childCollectionId = res.right.createRESTChildUserCollection.id

      const returnedData = res.right.createRESTChildUserCollection.data
        ? JSON.parse(res.right.createRESTChildUserCollection.data)
        : {
            auth: {
              authType: "inherit",
              authActive: true,
            },
            headers: [],
            variables: [],
            _ref_id: generateUniqueRefId("coll"),
            description: null,
          }

      collection.id = childCollectionId
      collection._ref_id = returnedData._ref_id ?? generateUniqueRefId("coll")
      collection.auth = returnedData.auth
      collection.headers = returnedData.headers
      parentCollectionID = childCollectionId
      collection.variables = returnedData.variables
      collection.description = returnedData.description ?? null

      removeDuplicateRESTCollectionOrFolder(
        childCollectionId,
        `${collectionPath}`
      )
    } else {
      parentCollectionID = undefined
      return
    }
  }

  // create the requests
  if (parentCollectionID) {
    for (const request of collection.requests) {
      const res = await createRESTUserRequest(
        request.name,
        JSON.stringify(request),
        parentCollectionID
      )

      if (res && E.isRight(res)) {
        const requestId = res.right.createRESTUserRequest.id

        request.id = requestId
      }
    }
  }

  // create the folders aka child collections
  if (parentCollectionID) {
    for (const [index, folder] of collection.folders.entries()) {
      await recursivelySyncCollections(
        folder,
        `${collectionPath}/${index}`,
        parentCollectionID
      )
    }
  }
}

// TODO: generalize this
// TODO: ask backend to send enough info on the subscription to not need this
export const collectionReorderOrMovingOperations: {
  sourceCollectionID: string
  destinationCollectionID?: string
  reorderOperation: {
    fromPath: string
    toPath?: string
  }
}[] = []

type OperationStatus = "pending" | "completed"

type OperationCollectionRemoved = {
  type: "COLLECTION_REMOVED"
  collectionBackendID: string
  status: OperationStatus
}

export const restCollectionsOperations: Array<OperationCollectionRemoved> = []

export async function ensurePathSynced(
  path: string | number | null,
  collectionStore: typeof restCollectionStore | typeof graphqlCollectionStore,
  recursivelySyncFn: (
    collection: HoppCollection,
    collectionPath: string,
    parentUserCollectionID?: string
  ) => Promise<void>
): Promise<boolean> {
  if (path === null || path === undefined || path === "") return true

  const collections = collectionStore.value.state
  const pathIndexes =
    typeof path === "number"
      ? [path]
      : path.split("/").map((index) => parseInt(index))

  let highestUnsyncedPath: number[] | null = null
  let parentID: string | undefined = undefined

  for (let i = 0; i < pathIndexes.length; i++) {
    const subPath = pathIndexes.slice(0, i + 1)
    const collection = navigateToFolderWithIndexPath(collections, subPath)
    if (!collection) break

    if (!collection.id) {
      highestUnsyncedPath = subPath
      break
    } else {
      parentID = collection.id
    }
  }

  if (highestUnsyncedPath) {
    const collectionToSync = navigateToFolderWithIndexPath(
      collections,
      highestUnsyncedPath
    )
    if (collectionToSync) {
      await recursivelySyncFn(
        collectionToSync,
        highestUnsyncedPath.join("/"),
        parentID
      )
      const targetCollection = navigateToFolderWithIndexPath(
        collections,
        pathIndexes
      )
      return !!targetCollection?.id
    }
  }

  return true
}

const ensureRESTPathSynced = (path: string | number | null) =>
  ensurePathSynced(path, restCollectionStore, recursivelySyncCollections)

export const storeSyncDefinition: StoreSyncDefinitionOf<
  typeof restCollectionStore
> = {
  async appendCollections({ entries }) {
    if (entries.length === 0) return

    // Transform collections to backend format
    const transformedCollections = entries.map(transformCollectionForBackend)

    // Use the bulk import API instead of individual calls
    const jsonString = JSON.stringify(transformedCollections)

    const result = await importUserCollectionsFromJSON(
      jsonString,
      ReqType.Rest,
      undefined // undefined for root collections
    )

    // The backend handles creating all collections and requests in a single transaction
    // The frontend collections will be updated through subscriptions

    if (E.isLeft(result)) {
      // Fallback to individual calls if bulk import fails
      let indexStart = restCollectionStore.value.state.length - entries.length

      for (const collection of entries) {
        await recursivelySyncCollections(collection, `${indexStart}`)
        indexStart++
      }
    }
  },
  async addCollection({ collection }) {
    // Use individual API for single collection creation (not import)
    const lastCreatedCollectionIndex =
      restCollectionStore.value.state.length - 1

    await recursivelySyncCollections(
      collection,
      `${lastCreatedCollectionIndex}`
    )
  },
  async removeCollection({ collectionID }) {
    if (collectionID) {
      await deleteUserCollection(collectionID)
    }
  },
  async editCollection({ partialCollection: collection, collectionIndex }) {
    const isSynced = await ensureRESTPathSynced(collectionIndex)
    if (!isSynced) return

    const collectionID = navigateToFolderWithIndexPath(
      restCollectionStore.value.state,
      [collectionIndex]
    )?.id

    const data = {
      auth: collection.auth,
      headers: collection.headers,
      variables: stripClientLocalValuesForWire(collection.variables),
      _ref_id: collection._ref_id,
      description: collection.description ?? null,
      preRequestScript: collection.preRequestScript ?? "",
      testScript: collection.testScript ?? "",
    }

    if (collectionID) {
      updateUserCollection(collectionID, collection.name, JSON.stringify(data))
    }
  },

  sortRESTCollection({ collectionPath, sortOrder }) {
    // If collectionPath is empty, it means we're sorting the whole root collections else we're sorting a specific collection
    const collectionID =
      collectionPath !== null && collectionPath !== undefined
        ? navigateToFolderWithIndexPath(restCollectionStore.value.state, [
            collectionPath,
          ])?.id
        : null

    const order =
      sortOrder === "asc" ? SortOptions.TitleAsc : SortOptions.TitleDesc

    sortUserCollections(collectionID ?? null, order)
  },

  sortRESTFolder({ path, sortOrder }) {
    const collectionID = navigateToFolderWithIndexPath(
      restCollectionStore.value.state,
      path.split("/").map((index) => parseInt(index))
    )?.id

    if (collectionID) {
      const order =
        sortOrder === "asc" ? SortOptions.TitleAsc : SortOptions.TitleDesc

      sortUserCollections(collectionID, order)
    }
  },

  async addFolder({ name, path }) {
    const isSynced = await ensureRESTPathSynced(path)
    if (!isSynced) return

    const parentCollection = navigateToFolderWithIndexPath(
      restCollectionStore.value.state,
      path.split("/").map((index) => parseInt(index))
    )

    if (parentCollection) {
      const foldersLength = parentCollection.folders.length
      if (foldersLength > 0 && parentCollection.folders[foldersLength - 1].id) {
        return
      }
    }

    const parentCollectionBackendID = parentCollection?.id

    if (parentCollectionBackendID) {
      const res = await createRESTChildUserCollection(
        name,
        parentCollectionBackendID
      )

      if (E.isRight(res)) {
        const { id } = res.right.createRESTChildUserCollection

        // Always try to assign the ID to the last created folder
        const foldersLength = parentCollection.folders.length
        if (foldersLength > 0) {
          const lastFolderIndex = foldersLength - 1
          const lastFolder = parentCollection.folders[lastFolderIndex]

          // Only assign ID if the folder doesn't already have one (avoid overwriting)
          if (!lastFolder.id) {
            lastFolder.id = id
            removeDuplicateRESTCollectionOrFolder(
              id,
              `${path}/${lastFolderIndex}`
            )
          }
        }
      }
    }
  },
  async editFolder({ folder, path }) {
    const isSynced = await ensureRESTPathSynced(path)
    if (!isSynced) return

    const folderID = navigateToFolderWithIndexPath(
      restCollectionStore.value.state,
      path.split("/").map((index) => parseInt(index))
    )?.id

    const folderName = folder.name
    const data = {
      auth: folder.auth,
      headers: folder.headers,
      variables: stripClientLocalValuesForWire(folder.variables),
      _ref_id: folder._ref_id,
      description: folder.description,
      preRequestScript: folder.preRequestScript ?? "",
      testScript: folder.testScript ?? "",
    }
    if (folderID) {
      updateUserCollection(folderID, folderName, JSON.stringify(data))
    }
  },
  async removeFolder({ folderID }) {
    if (folderID) {
      await deleteUserCollection(folderID)
    }
  },
  async moveFolder({ destinationPath, path }) {
    const { newSourcePath, newDestinationPath } = getPathsAfterMoving(
      path,
      destinationPath ?? undefined
    )

    if (newSourcePath) {
      const collections = restCollectionStore.value.state
      const sourceCollection = navigateToFolderWithIndexPath(
        collections,
        newSourcePath.split("/").map((index) => parseInt(index))
      )
      const destCollection =
        destinationPath && newDestinationPath
          ? navigateToFolderWithIndexPath(
              collections,
              newDestinationPath.split("/").map((index) => parseInt(index))
            )
          : null

      const wasSourceSynced = !!sourceCollection?.id
      const wasDestSynced = destinationPath ? !!destCollection?.id : true

      const isSourceSynced = await ensureRESTPathSynced(newSourcePath)
      const isDestSynced = newDestinationPath
        ? await ensureRESTPathSynced(newDestinationPath)
        : true

      if (!isSourceSynced || !isDestSynced) return

      if (!wasSourceSynced || !wasDestSynced) return

      const sourceCollectionID = navigateToFolderWithIndexPath(
        restCollectionStore.value.state,
        newSourcePath.split("/").map((index) => parseInt(index))
      )?.id

      const destinationCollectionID = destinationPath
        ? newDestinationPath &&
          navigateToFolderWithIndexPath(
            restCollectionStore.value.state,
            newDestinationPath.split("/").map((index) => parseInt(index))
          )?.id
        : undefined

      if (sourceCollectionID) {
        await moveUserCollection(sourceCollectionID, destinationCollectionID)
      }
    }
  },
  async duplicateCollection({ collectionSyncID }) {
    if (collectionSyncID) {
      const res = await duplicateUserCollection(collectionSyncID, ReqType.Rest)

      if (E.isRight(res)) {
        applyDuplicatedCollectionResult(
          "REST",
          collectionSyncID,
          res.right.duplicateUserCollection.exportedCollection
        )
      }
    }
  },
  async editRequest({ path, requestIndex, requestNew }) {
    const isSynced = await ensureRESTPathSynced(path)

    const folder = navigateToFolderWithIndexPath(
      restCollectionStore.value.state,
      path.split("/").map((index) => parseInt(index))
    )
    if (!folder) return

    const request = folder.requests[requestIndex]
    if (!request) return

    // Unified workspace: REST mutation handles both kinds — backend stores the request as opaque JSON in a REST row.
    const typed = requestNew as HoppRESTRequest | HoppGQLRequest

    if (request.id) {
      editUserRequest(request.id, typed.name, JSON.stringify(typed))
    } else {
      if (isSynced && folder.id) {
        const res = await createRESTUserRequest(
          typed.name,
          JSON.stringify(typed),
          folder.id
        )
        if (res && E.isRight(res)) {
          request.id = res.right.createRESTUserRequest.id
        }
      }
    }
  },
  async saveRequestAs({ path, request }) {
    const isSynced = await ensureRESTPathSynced(path)
    if (!isSynced) return

    const folder = navigateToFolderWithIndexPath(
      restCollectionStore.value.state,
      path.split("/").map((index) => parseInt(index))
    )

    if (folder) {
      const requestsLength = folder.requests.length
      if (requestsLength > 0 && folder.requests[requestsLength - 1].id) {
        return
      }
    }

    const parentCollectionBackendID = folder?.id

    if (parentCollectionBackendID) {
      // See `editRequest` above — REST mutation handles both kinds.
      const typed = request as HoppRESTRequest | HoppGQLRequest
      const res = await createRESTUserRequest(
        typed.name,
        JSON.stringify(typed),
        parentCollectionBackendID
      )

      if (E.isRight(res)) {
        const { id } = res.right.createRESTUserRequest

        // Find the last request that doesn't have an ID (the newly added one)
        const requestsLength = folder.requests.length
        if (requestsLength > 0) {
          const lastRequestIndex = requestsLength - 1
          const lastRequest = folder.requests[lastRequestIndex]

          // Only assign ID if the request doesn't already have one
          if (!lastRequest.id) {
            lastRequest.id = id
            removeDuplicateRESTCollectionOrFolder(
              id,
              `${path}/${lastRequestIndex}`,
              "request"
            )
          }
        }
      }
    }
  },
  async removeRequest({ requestID }) {
    if (requestID) {
      await deleteUserRequest(requestID)
    }
  },
  async moveRequest({ destinationPath, path, requestIndex }) {
    const collections = restCollectionStore.value.state
    const sourceCollection = navigateToFolderWithIndexPath(
      collections,
      path.split("/").map((index) => parseInt(index))
    )
    const destCollection = navigateToFolderWithIndexPath(
      collections,
      destinationPath.split("/").map((index) => parseInt(index))
    )

    const wasSourceSynced = !!sourceCollection?.id
    const wasDestSynced = !!destCollection?.id

    const isSourceSynced = await ensureRESTPathSynced(path)
    const isDestSynced = await ensureRESTPathSynced(destinationPath)
    if (!isSourceSynced || !isDestSynced) return

    if (!wasSourceSynced || !wasDestSynced) return

    moveOrReorderRequests(requestIndex, path, destinationPath)
  },
  async updateRequestOrder({
    destinationCollectionPath,
    destinationRequestIndex,
    requestIndex,
  }) {
    /**
     * currently the FE implementation only supports reordering requests between the same collection,
     * so destinationCollectionPath and sourceCollectionPath will be same
     */
    const collections = restCollectionStore.value.state
    const collection = navigateToFolderWithIndexPath(
      collections,
      destinationCollectionPath.split("/").map((index) => parseInt(index))
    )
    const wasSynced = !!collection?.id

    const isSynced = await ensureRESTPathSynced(destinationCollectionPath)
    if (!isSynced) return

    if (!wasSynced) return

    moveOrReorderRequests(
      requestIndex,
      destinationCollectionPath,
      destinationCollectionPath,
      destinationRequestIndex ?? undefined
    )
  },
  async updateCollectionOrder({
    collectionIndex: collectionPath,
    destinationCollectionIndex: destinationCollectionPath,
  }) {
    const collections = restCollectionStore.value.state

    const sourcePathIndexes = getParentPathIndexesFromPath(collectionPath)
    const sourceCollectionIndex = getCollectionIndexFromPath(collectionPath)

    const destinationCollectionIndex = !!destinationCollectionPath
      ? getCollectionIndexFromPath(destinationCollectionPath)
      : undefined

    let updatedCollectionIndexs:
      | [newSourceIndex: number, newDestinationIndex: number | undefined]
      | undefined

    if (
      (sourceCollectionIndex || sourceCollectionIndex == 0) &&
      (destinationCollectionIndex || destinationCollectionIndex == 0)
    ) {
      updatedCollectionIndexs = getIndexesAfterReorder(
        sourceCollectionIndex,
        destinationCollectionIndex
      )
    } else if (sourceCollectionIndex || sourceCollectionIndex == 0) {
      if (sourcePathIndexes.length == 0) {
        // we're reordering root collections
        updatedCollectionIndexs = [collections.length - 1, undefined]
      } else {
        const sourceCollection = navigateToFolderWithIndexPath(collections, [
          ...sourcePathIndexes,
        ])

        if (sourceCollection && sourceCollection.folders.length > 0) {
          updatedCollectionIndexs = [
            sourceCollection.folders.length - 1,
            undefined,
          ]
        }
      }
    }

    const sourceCollectionID =
      updatedCollectionIndexs &&
      navigateToFolderWithIndexPath(collections, [
        ...sourcePathIndexes,
        updatedCollectionIndexs[0],
      ])?.id

    const destinationCollectionID =
      updatedCollectionIndexs &&
      (updatedCollectionIndexs[1] || updatedCollectionIndexs[1] == 0)
        ? navigateToFolderWithIndexPath(collections, [
            ...sourcePathIndexes,
            updatedCollectionIndexs[1],
          ])?.id
        : undefined

    if (sourceCollectionID) {
      await updateUserCollectionOrder(
        sourceCollectionID,
        destinationCollectionID
      )
    }
  },
}

export const collectionsSyncer = getSyncInitFunction(
  restCollectionStore,
  storeSyncDefinition,
  () => settingsStore.value.syncCollections,
  getSettingSubject("syncCollections")
)

export async function moveOrReorderRequests(
  requestIndex: number,
  path: string,
  destinationPath: string,
  nextRequestIndex?: number,
  requestType: "REST" | "GQL" = "REST"
) {
  const { collectionStore } = getStoreByCollectionType(requestType)

  const sourceCollectionBackendID = navigateToFolderWithIndexPath(
    collectionStore.value.state,
    path.split("/").map((index) => parseInt(index))
  )?.id

  const destinationCollection = navigateToFolderWithIndexPath(
    collectionStore.value.state,
    destinationPath.split("/").map((index) => parseInt(index))
  )

  const destinationCollectionBackendID = destinationCollection?.id

  let requestBackendID: string | undefined

  let nextRequestBackendID: string | undefined

  // `!== undefined` (not truthy) so position-0 drops still take the reorder path.
  if (nextRequestIndex !== undefined) {
    // reordering
    const [newRequestIndex, newDestinationIndex] = getIndexesAfterReorder(
      requestIndex,
      nextRequestIndex
    )

    requestBackendID =
      destinationCollection?.requests[newRequestIndex]?.id ?? undefined

    nextRequestBackendID =
      destinationCollection?.requests[newDestinationIndex]?.id ?? undefined
  } else {
    // moving
    const requests = destinationCollection?.requests
    requestBackendID =
      requests && requests.length > 0
        ? requests[requests.length - 1]?.id
        : undefined
  }

  if (
    sourceCollectionBackendID &&
    destinationCollectionBackendID &&
    requestBackendID
  ) {
    await moveUserRequest(
      sourceCollectionBackendID,
      destinationCollectionBackendID,
      requestBackendID,
      nextRequestBackendID
    )
  }
}

function getParentPathIndexesFromPath(path: string) {
  const indexes = path.split("/")
  indexes.pop()
  return indexes.map((index) => parseInt(index))
}

export function getCollectionIndexFromPath(collectionPath: string) {
  const sourceCollectionIndexString = collectionPath.split("/").pop()
  const sourceCollectionIndex = sourceCollectionIndexString
    ? parseInt(sourceCollectionIndexString)
    : undefined

  return sourceCollectionIndex
}

/**
 * the sync function is called after the reordering has happened on the store
 * because of this we need to find the new source and destination indexes after the reordering
 */
function getIndexesAfterReorder(
  oldSourceIndex: number,
  oldDestinationIndex: number
): [newSourceIndex: number, newDestinationIndex: number] {
  // Source Becomes Destination -1
  // Destination Remains Same
  if (oldSourceIndex < oldDestinationIndex) {
    return [oldDestinationIndex - 1, oldDestinationIndex]
  }

  // Source Becomes The Destination
  // Destintion Becomes Source + 1
  if (oldSourceIndex > oldDestinationIndex) {
    return [oldDestinationIndex, oldDestinationIndex + 1]
  }

  throw new Error("Source and Destination are the same")
}

/**
 * the sync function is called after moving a folder has happened on the store,
 * because of this the source index given to the sync function is not the live one
 * we need to find the new source index after the moving
 */
function getPathsAfterMoving(sourcePath: string, destinationPath?: string) {
  if (!destinationPath) {
    return {
      newSourcePath: `${restCollectionStore.value.state.length - 1}`,
      newDestinationPath: destinationPath,
    }
  }

  const sourceParentPath = getParentPathFromPath(sourcePath)
  const destinationParentPath = getParentPathFromPath(destinationPath)

  const isSameParentPath = sourceParentPath === destinationParentPath

  let newDestinationPath: string

  if (isSameParentPath) {
    const sourceIndex = getCollectionIndexFromPath(sourcePath)
    const destinationIndex = getCollectionIndexFromPath(destinationPath)

    if (
      (sourceIndex || sourceIndex == 0) &&
      (destinationIndex || destinationIndex == 0) &&
      sourceIndex < destinationIndex
    ) {
      newDestinationPath = destinationParentPath
        ? `${destinationParentPath}/${destinationIndex - 1}`
        : `${destinationIndex - 1}`
    } else {
      newDestinationPath = destinationPath
    }
  } else {
    newDestinationPath = destinationPath
  }

  const destinationFolder = navigateToFolderWithIndexPath(
    restCollectionStore.value.state,
    newDestinationPath.split("/").map((index) => parseInt(index))
  )

  const newSourcePath = destinationFolder
    ? `${newDestinationPath}/${destinationFolder?.folders.length - 1}`
    : undefined

  return {
    newSourcePath,
    newDestinationPath,
  }
}

function getParentPathFromPath(path: string | undefined) {
  const indexes = path ? path.split("/") : []
  indexes.pop()

  return indexes.join("/")
}

export function getStoreByCollectionType(type: "GQL" | "REST") {
  const isGQL = type == "GQL"

  const collectionStore = isGQL ? graphqlCollectionStore : restCollectionStore

  return { collectionStore }
}