require 'commander'
require_relative './version'

module Nadir
  class NadirTestException < StandardError; end
  class CLI
    include Commander::Methods

    def run
      program :name, 'nadir'
      program :version, Nadir::VERSION
      program :description, 'Ruby/Rails client for Nadir'

      never_trace!

      command 'setup' do |c|
        c.syntax = 'nadir setup API-KEY'
        c.description = 'Creates Nadir\'s configuration file config/nadir.yml and populates it with the provided API-KEY.'
        c.action do |args, _options|
          api_key = args[0]

          if File.exist? config_file_path
            say_error 'Nadir config file already exists.'

            exit(0)
          end

          unless api_key
            say_error 'Please provide an API KEY.'

            exit(0)
          end

          configuration_file = <<~YAML
          ---
          api_key: #{api_key}
          YAML

          File.open(config_file_path, 'w') { |file| file.write(configuration_file) }

          say_success <<~MSG
          Nadir client configured successfully!

          Test the integration by sending a test notification:

          bundle exec nadir test-notify

          If all is well, you'll see the test notification in https://nadir.dev.
          MSG
        end
      end

      command 'test-notify' do |c|
        c.syntax = 'nadir test-notify'
        c.description = 'Send a test notification to Nadir'
        c.action do |args, _options|
          require File.expand_path('config/environment')

          Nadir.configure do |config|
            config.enabled_for << 'development'
          end

          begin
            raise NadirTestException.new('Test message')
          rescue NadirTestException => e
            if Nadir.notify e, location: 'nadir test-notify'
              say_success 'Test notification sent successfully.'
            else
              say_error 'Test notification could not be delivered.'
            end

            Nadir::Transport::HTTPAsync.shut_down
          end
        end
      end

      run!
    end

    def config_file_path
      File.expand_path 'config/nadir.yml'
    end

    def say_success(message)
      say color(message, :green)
    end

    def say_error(message)
      say color(message, :red)
    end
  end
end