profile = "vcs/[email protected]"
provider = "github"

"""
UserRepos map. Returns all github repositories of specified user
"""
map UserRepos {
  call Paginate(
    user = input.user,
  ) {
    return map error if (outcome.error) outcome.error
    return map result { repos = outcome.data.repositories }
  }
}

operation Paginate {
  data = []
  page = 1
  //Hack to create a while with maximum loop count - use Superface stdlib instead
  call foreach(_x of Array(2**32 -1)) FetchRepos(user = args.user, page = page) {
    fail if (outcome.error) outcome.error
    data = [...data, ...outcome.data.repositories]
  
    page = page + 1
    return if (outcome.data.repositories.length === 0) {
      repositories: data,
      statusCode: 200
    }
  }
  return {
    repositories: data,
    statusCode: 200
  }
}


operation FetchRepos {
  http GET "/users/{args.user}/repos" {
    request {
      query {
        page = args.page
      }
    }
    response {
      fail if(statusCode !== 200){
      message: body.message,
      description: body.documentation_url,
      statusCode: statusCode
      }
      return {
        repositories: body.map((r) => {
          return {
            name: r.name,
            description: r.description === null ? undefined : r.description
          }
        }),
        statusCode: statusCode
      }
    }
  }
}