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, router }) => {
    if (to.fullPath.startsWith('/external-url/')) {
      const path = to.path.startsWith('/') ? to.path.substring(1) : to.path

      let redirectionData = path.split('/')

      const contentType = redirectionData[1]
      const uuid = redirectionData[2]

      const redirectionRoute = routesListing[contentType]
      let redirectionParams = redirectionRoute?.params
      const redirectionQuery = uuid && redirectionRoute?.query

      if (
        [
          'sops',
          'rops',
          'documents',
          'declined_documents',
          'photo',
          'folders'
        ].includes(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)
        }
      } else if (redirectionParams) {
        try {
          const { data } = await http.get(`content/${contentType}`, {
            fields: redirectionParams,
            filters: {
              limit: 1,
              'status:eq': 1,
              'uuid:eq': uuid
            }
          })

          for (const param in data[0]) {
            redirectionParams[param] = Array.isArray(data[0][param])
              ? data[0][param][0]
              : data[0][param]
          }
        } catch (err) {
          throw new Error(err)
        }

        next(
          formatHref(
            {
              name: redirectionRoute.name,
              params: !!redirectionParams && redirectionParams,
              query: !!redirectionQuery && redirectionQuery
            },
            store.getters.getCurrentLang
          )
        )
      } else {
        router.push('/')
      }
    }
  }
}
