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

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

    if (!brand) next()

    let useLhgBrand = brand.code === LHG_GROUP_CODE

    if (!useLhgBrand && to?.name?.includes('LHGPage')) {
      try {
        const { data: lhgBrand } = 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: { 'status:eq': 1, limit: 1, 'code:eq': LHG_GROUP_CODE }
        })

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

        storage.set('brand', lhgBrand[0])

        brand = lhgBrand[0]
        useLhgBrand = true
      } catch (err) {
        throw new Error(err)
      }
    }

    if (useLhgBrand && to.path === '/') {
      next(
        formatHref(
          {
            name: 'LHGPage'
          },
          store.getters.getCurrentLang
        )
      )
    }
  }
}
