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

export default {
  pos: 0,
  group: 'postLogin',
  fn: async ({ to, next, store }) => {
    const brand = storage.get('brand')

    if (storage.get('language-change')?.isChangingLang && brand) {
      const targetLang = storage.get('language-change').targetLang
      const { data } = await http.get(
        'content/brands',
        {
          filters: {
            'uuid:eq': brand?.uuid || '',
            limit: 1
          },
          fields: ['admin', 'langcode']
        },
        { useLangcode: false }
      )

      const currentBrandLang = Object.values(
        data?.[0]?.admin?.translations
      ).find(translation => translation?.uuid === brand?.uuid)?.langcode

      if (currentBrandLang && targetLang && currentBrandLang !== targetLang) {
        try {
          const { data: targetBrand } = await http.get(
            'content/brands',
            {
              fields: [
                'uuid',
                'title',
                'banner_image',
                'brand_logo',
                'header_logo',
                'menu_icon',
                'code',
                'weight',
                'legal_mentions',
                'secondary_color',
                'primary_color',
                'users'
              ],
              filters: {
                'uuid:eq':
                  data?.[0]?.admin?.translations?.[targetLang]?.uuid ||
                  brand?.uuid ||
                  ''
              }
            },
            { useLangcode: false }
          )

          store.commit('setSpecificUserInfos', {
            key: 'brand',
            value: targetBrand[0]
          })

          storage.set('brand', targetBrand[0])
        } catch (err) {
          throw new Error(err)
        }
      }
    }

    if (
      !storage.get('target-brand-page') ||
      (storage.get('target-brand-page') === '/' && storage.get('target-page'))
    ) {
      storage.set('target-brand-page', storage.get('target-page'))
    }

    if (!brand && !to.name.includes('Brands')) {
      next(formatHref({ name: 'Brands' }, store.getters.getCurrentLang))
    }
  }
}
