type RoleLike = string | { code?: string | null; name?: string | null; name_en?: string | null; name_ar?: string | null }

type UserLike = {
  role?: string | null
  roles?: RoleLike[] | null
  permissions?: string[] | null
  user_type?: string | null
}

function roleCode(role: RoleLike | null | undefined): string | null {
  if (!role) return null
  if (typeof role === "string") return role
  return role.code ?? role.name ?? role.name_en ?? role.name_ar ?? null
}

export function isSuperAdminUser(user?: UserLike | null): boolean {
  const roles = [
    user?.role,
    ...(user?.roles ?? []).map(roleCode),
  ].filter(Boolean)

  return roles.includes("super_admin")
}

export function effectivePermissions(user?: UserLike | null): string[] {
  const permissions = user?.permissions ?? []
  return isSuperAdminUser(user) ? Array.from(new Set(["*", ...permissions])) : permissions
}

export function hasPermission(user: UserLike | null | undefined, permission: string): boolean {
  const permissions = effectivePermissions(user)
  return permissions.includes("*") || permissions.includes(permission)
}
