import { computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import { effectivePermissions } from '../utils/admin-access';

export function usePermissions() {
  const auth = useAuthStore();

  const role = computed(() => auth.user.value?.role ?? null);
  const permissions = computed(() =>
    effectivePermissions(auth.user.value?.role, auth.user.value?.permissions),
  );
  const isSuperAdmin = computed(() => role.value === 'SUPER_ADMIN');

  function hasPermission(...codes: string[]): boolean {
    if (!auth.isAdmin.value) return false;
    if (isSuperAdmin.value) return true;
    const set = permissions.value;
    return codes.some((c) => set.includes(c));
  }

  function hasAllPermissions(...codes: string[]): boolean {
    if (!auth.isAdmin.value) return false;
    if (isSuperAdmin.value) return true;
    const set = permissions.value;
    return codes.every((c) => set.includes(c));
  }

  function firstAllowedPath(candidates: { path: string; permissions: string[] }[]): string | null {
    for (const item of candidates) {
      if (hasPermission(...item.permissions)) return item.path;
    }
    return null;
  }

  return {
    role,
    permissions,
    isSuperAdmin,
    hasPermission,
    hasAllPermissions,
    firstAllowedPath,
  };
}
