# frozen_string_literal: true

require '/data_importer/lib/github_api/github_api'
module GithubApi
  class SecurityAdvisory
    SecurityAdvisoryQuery = GithubApi::Client.parse <<-'GRAPHQL'
    query($ghsa_id: String!) {
        securityAdvisory(ghsaId: $ghsa_id) {
            ghsaId
            summary
            severity
            description
            cvss {
                vectorString
            }
            origin
            permalink
            notificationsPermalink
            updatedAt
            publishedAt
            cwes(first: 100) {
                edges {
                    node {
                        cweId
                        description
                    }
                }
            }
            references {
                url
            }
            vulnerabilities(first: 100) {
                edges {
                    node {
                        package {
                            name
                            ecosystem
                        }
                        severity
                        updatedAt
                        vulnerableVersionRange
                    }
                }
            }
        }
    }
    GRAPHQL

    def self.find(ghsa_id)
      # Retryable.retryable(tries: 3, on: QueryExecutionError, sleep: lambda { |n| 4**n } ) do
      response = GithubApi::Client.query(SecurityAdvisoryQuery, variables: { ghsa_id: ghsa_id })
      if response.errors.any?
        raise QueryExecutionError, response.errors[:data].join(', ')
      else
        response.data.security_advisory
      end
      # end
    end
  end
end

class QueryExecutionError < StandardError; end