# frozen_string_literal: true

require 'graphql'
require 'graphql/client'

require_relative 'http'

module GraphQLSchemaCompatibility
  module Github
    module SchemaDumper
      SCHEMA_DUMP_PATH = "#{__dir__}/github.graphql"

      def self.dump(token:)
        # This can be simplified if https://github.com/github/graphql-client/pull/254 merges
        introspection_query = GraphQL.parse(GraphQL::Introspection.query)
        result = GraphQLSchemaCompatibility::Github::HTTP.execute(
          document: introspection_query,
          context: { token: token }
        ).to_h

        raise "Failed to load schema: #{JSON.pretty_generate(result['errors'])}" if result['errors'].present?

        schema = GraphQL::Schema.from_introspection(result)
        IO.write(SCHEMA_DUMP_PATH, schema.to_definition)

        SCHEMA_DUMP_PATH
      end
    end
  end
end
