import { storage } from '@inside-library/helpers/Storage'
import { http } from '@inside-library/helpers/Http'
import { isSuperAdmin, isAdmin } from '@inside-library/helpers/Rights'

export const franchisedSpacesGuard = async ({ next, to, router }) => {
  const user = storage.get('current-user')

  const { data } = await http.get('content/users', {
    fields: [{ franchised_spaces: ['uuid', 'slug'] }],
    filters: { 'uuid:eq': storage.get('current-user').uuid, 'status:eq': 1 }
  })

  const hasAccess = () => {
    if (to.name === 'SpacePage' || to.name === 'SpaceVisitReport') {
      if (
        user.permissions.roles.includes('Franchisé') &&
        to.path.includes(data[0]?.franchised_spaces?.slug[0])
      ) {
        return true
      }
    } else if (to.name === 'SpacesListing') {
      if (
        user.permissions.roles.includes('Franchisé') &&
        data[0]?.franchised_spaces
      ) {
        return true
      }

      if (
        user.permissions.roles.includes('Rédacteur en chef') ||
        user.permissions.roles.includes('Rédacteur')
      ) {
        return true
      }
    }

    return false
  }

  if (isSuperAdmin() || isAdmin()) {
    return
  }

  if (
    !hasAccess() &&
    !user.permissions.roles.includes('Rédacteur en chef') &&
    !user.permissions.roles.includes('Rédacteur')
  ) {
    router.push({
      name: 'ErrorPage',
      params: {
        code: '403'
      }
    })
  }

  next()
}
