# frozen_string_literal: true

require 'trollop'

module ArticleFixtureGen
  module Exe
    module Trollop
      # Validates attribute values using evaled code from YAML file.
      class Validator
        def self.call(option_data)
          new(option_data).call
        end

        def call
          Internals.validations.map do |validation|
            validate(validation)
          end
          option_data
        end

        protected

        def initialize(option_data)
          @option_data = option_data
          self
        end

        private

        attr_reader :option_data

        def options
          option_data.options
        end

        # Reek calls out :reek:FeatureEnvy on `validation`. Pffft.
        def validate(validation)
          die_params = [validation[:key], validation[:str]]
          ::Trollop.die(*die_params) if validation_failed?(validation)
          true
        end

        def validation_failed?(validation)
          validation_proc_for(validation).call options
        end

        def validation_proc_for(validation)
          # rubocop:disable Lint/Eval
          eval(validation[:fails_with])
          # rubocop:enable Lint/Eval
        end

        # Stateless methods
        module Internals
          def self.validations
            YAML.load_file 'data/validations.yml'
          end
        end
        private_constant :Internals
      end # class ArticleFixtureGen::Exe::Trollop::Validator
    end
  end
end
