module Rspec::Dunlop::SelfTest::Integrity
  extend ActiveSupport::Concern
  Pair = Struct.new(:key, :value)

  # it{ should be_properly_installed_and_configured }
  def properly_installed_and_configured?
    if defined?(TargetFile)
      target_file_valid?
    end
    if defined?(SourceFile)
      source_file_valid?
    end
    true
  end

  def target_file_valid?
    # Naming uniqueness
    test_duplicate_model_names TargetFile.classes
  end

  def source_file_valid?
    test_duplicate_model_names SourceFile.classes
  end

  def test_duplicate_model_names(models)
    singular_names = models.map{|cls| Pair.new(cls.name, cls.model_name.human) }
    duplicate_singular_names = singular_names.group_by(&:value).select { |k, vs| vs.size > 1 }
    if duplicate_singular_names.present?
      message = duplicate_singular_names.map{|name, pairs| "The models #{pairs.map(&:key).join(', ')} have a duplicate singular name #{name}"}.join("\n")
      raise DunlopValidationError.new(message)
    end

    plural_names = models.map{|cls| Pair.new(cls.name, cls.model_name.human_plural) }
    duplicate_plural_names = plural_names.group_by(&:value).select { |k, vs| vs.size > 1 }
    if duplicate_plural_names.present?
      message = duplicate_plural_names.map{|name, pairs| "The models #{pairs.map(&:key).join(', ')} have a duplicate plural name #{name}"}.join("\n")
      raise DunlopValidationError.new(message)
    end
  end

  class DunlopValidationError < StandardError

  end
end
