# frozen_string_literal: true

require "pagerduty/version"
require "pagerduty/http_transport"
require "pagerduty/events_api_v1"
require "pagerduty/events_api_v2"

class PagerdutyException < StandardError
  attr_reader :pagerduty_instance, :api_response

  def initialize(instance, response, message)
    super(message)
    @pagerduty_instance = instance
    @api_response = response
  end
end

module Pagerduty
  # Build an instance that will send API calls to the specified Pagerduty
  # Events API version.
  #
  # @example Build an instance for the Events API version 1
  #   pagerduty = Pagerduty.build(
  #     integration_key: "<integration-key>",
  #     api_version:     1,
  #   )
  #
  # @example Build an instance using an HTTP proxy for API requests
  #   pagerduty = Pagerduty.build(
  #     integration_key: "<integration-key>",
  #     api_version:     1,
  #     http_proxy:      {
  #       host:     "my.http.proxy.local",
  #       port:     3128,
  #       username: "<my-proxy-username>",
  #       password: "<my-proxy-password>",
  #     }
  #   )
  #
  # @option config [String] integration_key Authentication key for connecting
  #   to PagerDuty. A UUID expressed as a 32-digit hexadecimal number.
  #   Integration keys are generated by creating a new service, or creating a
  #   new integration for an existing service in PagerDuty, and can be found on
  #   a service's Integrations tab. This option is required.
  #
  # @option config [String] api_version The version of the Pagerduty events API.
  #  The gem currently supports version 1 (`1`). This option is required.
  #
  # @option config [String] http_proxy.host The DNS name or IP address of the
  #   proxy host. If nil or unprovided an HTTP proxy will not be used.
  #
  # @option config [String] http_proxy.port The TCP port to use to access the
  #   proxy.
  #
  # @option config [String] http_proxy.username username if authorization is
  #   required to use the proxy.
  #
  # @option config [String] http_proxy.password password if authorization is
  #   required to use the proxy.
  #
  # @return [Pagerduty::EventsApiV1] the built instance.
  #
  # @raise [ArgumentError] If integration_key or api_version options are not
  #   provided. Or if the provided api_version is unsupported.
  #
  def self.build(config)
    raise ArgumentError, "integration_key not provided" unless config.key?(:integration_key)
    raise ArgumentError, "incident_key provided" if config.key?(:incident_key)

    version = config.fetch(:api_version) do
      raise ArgumentError, "api_version not provided"
    end
    events_api_class(version).new(config)
  end

  def self.events_api_class(version)
    class_name = "Pagerduty::EventsApiV#{version}"
    if const_defined?(class_name)
      const_get(class_name)
    else
      raise ArgumentError, "api_version #{version.inspect} not supported"
    end
  end
  private_class_method :events_api_class
end
