module Promotions
  module PromotionAudit
    class << self
      def new_audit(entity, resource)
        changesets = resource.attributes.except(:reporter, :id, :inserted_at, :updated_at, :created_on, :updated_on, :start_date_part, :start_time_part, :end_date_part, :end_time_part, :description_rendered).map do |key, value_hash|
          History::ChangeSet.new(
            attribute: key,
            old_value: nil,
            new_value: value_hash
          )
        end
        base_audit('create', resource, entity, changesets)
      end

      def delete_audit(entity, resource)
        changesets = resource.attributes.except(:reporter, :id, :inserted_at, :updated_at, :created_on, :updated_on, :start_date_part, :start_time_part, :end_date_part, :end_time_part, :description_rendered).map do |key, value_hash|
          History::ChangeSet.new(
            attribute: key,
            old_value: value_hash,
            new_value: nil
          )
        end

        base_audit('delete', resource, entity, changesets)
      end

      def update_audit(entity, resource)
        changesets = resource.changes.except(:id, :start_date_part, :start_date_time, :end_date_part, :end_time_part, :description_rendered).map do |key, value_hash|
          History::ChangeSet.new(
            attribute: key,
            old_value: value_hash[:old_value],
            new_value: value_hash[:new_value]
          )
        end

        base_audit('update', resource, entity, changesets)
      end

      def promotion_audit_params(entity, resource)
        return { resource_type: entity,
                 resource_id: resource.id }
      end

      private

      def base_audit(action, resource, entity, changes = [])
        promo_param = promotion_audit_params(entity, resource)
        History::Audit.new(
            action: action,
            user_type: "ldap_user",
            user_id: resource.reporter,
            resource_type: entity,
            resource_id: promo_param[:resource_id],
            changes: changes
        )
      end
    end
  end
end
