# frozen_string_literal: true

module Oauth
  module Util
    OAUTH_SETTINGS_KEYS = [:id_application, :oauth_application, :oauth_key].freeze

    class ExistingSettingsError < StandardError; end

    def self.register_apps(display_name, generated_by: name, output: $stdout)
      settings_path = Rails.root.join("config/settings.local.yml")

      check_not_already_registered!(settings_path, :output => output)

      user = User.find_by! :display_name => display_name

      model = Doorkeeper.config.application_model

      id_application = model.create(
        :name => "Local iD",
        :redirect_uri => "http://localhost:3000",
        :scopes => %w[read_prefs write_prefs write_api read_gpx write_gpx write_notes],
        :confidential => false,
        :owner => user
      )

      web_application = model.create(
        :name => "OpenStreetMap Web Site",
        :redirect_uri => "http://localhost:3000",
        :scopes => %w[write_api write_notes],
        :owner => user
      )

      File.open settings_path, "a" do |file|
        file << "\n" if settings_path.exist?
        file << <<~SETTINGS
          # generated by #{generated_by}
          # OAuth 2 Client ID for iD
          id_application: "#{id_application.uid}"
          # OAuth 2 Client ID for the web site
          oauth_application: "#{web_application.uid}"
          # OAuth 2 Client Secret for the web site
          oauth_key: "#{web_application.plaintext_secret}"
        SETTINGS
      end

      output.puts "Updated settings in #{settings_path}"
    end

    def self.check_not_already_registered!(path, opts = {})
      output = opts.fetch(:output, $stdout)
      already_defined_keys = OAUTH_SETTINGS_KEYS & Settings.keys

      return if already_defined_keys.empty?

      if path.exist?
        output.puts "The following settings are already defined (likely in #{path}):"
      else
        output.puts "The following settings are already defined:"
      end

      already_defined_keys.each do |key|
        output.puts "- #{key}"
      end

      output.puts "Delete or comment them out to regenerate."

      raise ExistingSettingsError
    end
  end
end
