module Rewards
  class CampaignsController < Rewards::BaseController

    def index
      authorize Campaign

      domain = params['campaign'].try(:[], 'domain')
      channel_id = params['campaign'].try(:[], 'channel_id')
      @campaigns =
        if domain.present?
          Campaign.find_by_domain(domain)
        elsif channel_id.present?
          Campaign.find_by_channel_id(channel_id)
        else
          []
        end
    end

    def invalidate_cache
      authorize Campaign

      domain = params['campaign'].try(:[], 'domain')
      unless domain.present?
        flash[:error] = 'Domain is required'
        return redirect_back
      end

      success = Campaign.invalidate_cache(domain)
      if success
        flash[:success] = "Successfully invalidated campaign cache for #{domain}"
      else
        flash[:error] = "Failed to invalidate campaign cache for #{domain}"
      end

      redirect_back
    end
  end
end
