import { createMongoAbility, AbilityBuilder } from '@casl/ability'

//  Read ability from localStorage
// * Handles auto fetching previous abilities if already logged in user
// ? You can update this if you store user abilities to more secure place
// ! Anyone can update localStorage so be careful and please update this
const userData = JSON.parse(localStorage.getItem('userData'))
const existingAbility = userData ? userData.ability : null

const {
  can,
  cannot,
  build,
  rules,
} = new AbilityBuilder(createMongoAbility)

export function getExistingAbility(userAbility) {
  switch (userAbility) {
    case 'visitor':
      can('read', 'all')
      cannot('read', 'management')
      break

    case 'manager':
      can('read', 'all')
      break

    default:
      can('read', 'all')
      cannot('read', 'visited')
      cannot('read', 'management')
      break
  }
  return rules
}

getExistingAbility(existingAbility)
export default build()
