import { formatHref } from '@inside-library/helpers/Langs'
import { http } from '@inside-library/helpers/Http'

import { routesListing } from '../constants/routesListing'

export default {
  pos: 0,
  group: 'postLogin',
  fn: async ({ to, next, store }) => {
    const contentRegex =
      /[a-zA-Z0-9_-]+#&ged\/[a-zA-Z0-9_-]+&modal\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/gm
    const contentRegex2 =
      /[a-zA-Z0-9_-]+#&modal\/folders\/[a-zA-Z0-9_-]+&ged\/[a-zA-Z0-9_-]+&modal\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/gm
    const contentRegex3 =
      /[a-zA-Z0-9_-]+#&modal\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+&ged\/[a-zA-Z0-9_-]+$/gm

    const folderRegex =
      /[a-zA-Z0-9_-]+#&modal\/folders\/[a-zA-Z0-9_-]+&ged\/[a-zA-Z0-9_-]+$/gm
    const folderRegex2 = /[a-zA-Z0-9_-]+#&ged\/[a-zA-Z0-9_-]+$/gm

    const mustBeRedirected = [
      contentRegex,
      contentRegex2,
      contentRegex3,
      folderRegex,
      folderRegex2
    ].some(reg => to.fullPath.match(reg))

    if (mustBeRedirected) {
      const redirectionType =
        to.fullPath.match(folderRegex) || to.fullPath.match(folderRegex2)
          ? 'folders'
          : 'content'

      let redirectionData = []
      let contentType = ''
      let uuid = ''
      let redirectionRoute = ''

      if (to.fullPath.match(contentRegex3)) {
        redirectionData = to.fullPath.split(/\/|&|#/).filter(el => el)

        contentType =
          redirectionType === 'folders'
            ? 'folders'
            : redirectionData[redirectionData.length - 4]
        uuid = redirectionData[redirectionData.length - 3]

        redirectionRoute = routesListing[contentType]
      } else {
        redirectionData = to.fullPath.split('/').filter(el => el)

        contentType =
          redirectionType === 'folders'
            ? 'folders'
            : redirectionData[redirectionData.length - 2]
        uuid = redirectionData[redirectionData.length - 1]

        redirectionRoute = routesListing[contentType]
      }

      try {
        store.commit('setCurrentModalContentType', contentType)

        const parent = await http.get(`content/tree/${contentType}/${uuid}`, {
          depth: contentType === 'declined_documents' ? 2 : 1
        })

        next(
          formatHref(
            {
              name: redirectionRoute.name,
              params:
                contentType === 'folders'
                  ? {
                      folder: parent.root?.slug || parent.content.slug,
                      ...(parent.root && { subFolder: parent.content.slug })
                    }
                  : {
                      folder: parent.root.slug,
                      ...(parent.parent && { subFolder: parent.parent.slug }),
                      document: parent.content.slug
                    }
            },
            store.getters.getCurrentLang
          )
        )
      } catch (err) {
        throw new Error(err)
      }
    }
  }
}
