# frozen_string_literal: true

require '/data_importer/lib/github_api/github_api'

module GithubApi
  class OwnerRepos
    OwnerReposQuery = GithubApi::Client.parse <<-'GRAPHQL'
		query($owner: String!, $cursor: String) {
			repositoryOwner(login: $owner) {
				repositories(
					first: 100
					ownerAffiliations: OWNER
					privacy: PUBLIC
					isFork: false
					isLocked: false
					orderBy: {field: NAME, direction: ASC}
					after: $cursor
				) {
					totalCount
					pageInfo {
						hasNextPage
						endCursor
					}
					nodes {
						name
						url
						homepageUrl
						mirrorUrl
						openGraphImageUrl
						resourcePath
						description
						descriptionHTML
						shortDescriptionHTML
						createdAt
						pushedAt
						updatedAt
						forkCount
						hasIssuesEnabled
						hasProjectsEnabled
						hasWikiEnabled
						isArchived
						isFork
						isInOrganization
						isLocked
						isMirror
						isPrivate
						isTemplate
						licenseInfo {
							id
						}
						lockReason
						usesCustomOpenGraphImage
						visibility
					}
				}
			}
		}
    GRAPHQL

    def self.find(username)
      # Retryable.retryable(tries: 3, on: QueryExecutionError, sleep: lambda { |n| 4**n } ) do
      response = GithubApi::Client.query(OwnerReposQuery, variables: { owner: username })
      if response.errors.any?
        raise QueryExecutionError, response.errors[:data].join(', ')
      else
        response.data.repository_owner.repositories.nodes.map(&:to_h)
      end
      # end
    end
  end
end

class QueryExecutionError < StandardError; end