# frozen_string_literal: true

require 'litany/meta_resource'

module Litany

  class << self
    # Triggers all resource definitions to become 'fully' baked.
    def finalize_resource_definitions
      MetaResource.descendants.each(&:finalize_resource_definition)
    end
  end

  # Base class for all AWS Resources
  class Resource < MetaResource
    def compile
      debug "Compiling #{self}..."

      segment = {
        Resources: {
          resource_name => {
            Type: cfn_type,
            Properties: properties
          }
        }
      }

      segment[:Resources][resource_name][:DependsOn] = depends_on if respond_to?(:depends_on)

      outputs = self.class.outputs
      unless outputs.empty?
        segment[:Outputs] ||= {}
        outputs.values.each do |output|
          next if output.skip_for?(self)

          key, data = output.data_for(self)
          segment[:Outputs][key] = data
        end
      end

      if taggable?
        tag :Name, output_name
        segment[:Resources][resource_name][:Properties][tag_key] = compiled_tags
      end

      segment
    end

    def properties
      {}
    end
  end
end
