<!--
 Access control component for fine-grained access control.
-->
<script lang="ts" setup>
import { computed } from 'vue';

import { useAccess } from './use-access';

interface Props {
  /**
   * Specified codes is visible
   * @default []
   */
  permissions?: string[];

  /**
   * 通过什么方式来控制组件，如果是 role，则传入角色，如果是 code，则传入权限码
   * @default 'role'
   */
  type?: 'code' | 'role';
}

defineOptions({
  name: 'AccessControl',
});

const props = withDefaults(defineProps<Props>(), {
  permissions: () => [],
  type: 'role',
});

const { hasAccessByCodes, hasAccessByRoles } = useAccess();

const hasAuth = computed(() => {
  const { permissions, type } = props;
  return type === 'role'
    ? hasAccessByRoles(permissions)
    : hasAccessByCodes(permissions);
});
</script>

<template>
  <slot v-if="!permissions"></slot>
  <slot v-else-if="hasAuth"></slot>
</template>
