src/derails/passive_aggressive/table_metadata.rb
# frozen_string_literal: true

module PassiveAggressive
  class TableMetadata # :nodoc:
    def initialize(klass, arel_table)
      @klass = klass
      @arel_table = arel_table
    end

    def primary_key
      klass&.primary_key
    end

    def type(column_name)
      arel_table.type_for_attribute(column_name)
    end

    def has_column?(column_name)
      klass&.columns_hash&.key?(column_name)
    end

    def associated_with(table_name)
      klass&._reflect_on_association(table_name)
    end

    def associated_table(table_name)
      reflection = klass._reflect_on_association(table_name) || klass._reflect_on_association(table_name.singularize)

      if !reflection && table_name == arel_table.name
        return self
      end

      if reflection
        association_klass = reflection.klass unless reflection.polymorphic?
      elsif block_given?
        association_klass = yield table_name
      end

      if association_klass
        arel_table = association_klass.arel_table
        arel_table = arel_table.alias(table_name) if arel_table.name != table_name
        TableMetadata.new(association_klass, arel_table)
      else
        type_caster = TypeCaster::Connection.new(klass, table_name)
        arel_table = Arel::Table.new(table_name, type_caster: type_caster)
        TableMetadata.new(nil, arel_table)
      end
    end

    def reflect_on_aggregation(aggregation_name)
      klass&.reflect_on_aggregation(aggregation_name)
    end
    alias :aggregated_with? :reflect_on_aggregation

    def predicate_builder
      if klass
        klass.predicate_builder.with(self)
      else
        PredicateBuilder.new(self)
      end
    end

    attr_reader :arel_table

    private
      attr_reader :klass
  end
end
