module Subscriptions
  class BadgesController < Subscriptions::BaseController
    def index
      channel_id = params[:channel_id]

      authorize Badge
      authorize BadgeTimeoutStatus

      @badges = Badge.existing_and_available_for(channel_id: channel_id)
      @timeout_status = BadgeTimeoutStatus.find_by(channel_id: channel_id)

      unless @timeout_status.persisted?
        flash.now[:error] = "Failed to retrieve timeout status for channel ID #{channel_id}"
      end
    end

    def create
      channel_id = params[:channel_id]

      @badge = Badge.new(badge_params)
      authorize @badge

      if @badge.save
        flash[:success] = "Successfully created Loyalty Badge for channel ID #{channel_id}"
      else
        flash[:error] = @badge.errors.full_messages.to_sentence
      end

      redirect_to subscriptions_channel_badges_path(channel_id: channel_id)
    end

    def destroy
      channel_id, id, channel_tenure_method_id = params[:channel_id], params[:id], params[:channel_tenure_method_id]

      authorize Badge

      @badge = Badge.new(channel_id: channel_id, id: id, channel_tenure_method_id: channel_tenure_method_id)

      if @badge.destroy
        flash[:success] = "Successfully deleted Loyalty Badge for channel ID #{channel_id}"
      else
        flash[:error] = @badge.errors.full_messages.to_sentence
      end

      redirect_to subscriptions_channel_badges_path(channel_id: channel_id)
    end

    private

    def badge_params
      permitted_params = [:image_1x, :image_2x, :image_4x, :required_tenure_months]
      attributes = params.require(:subscriptions_badge).permit(permitted_params)
      attributes[:channel_id] = params[:channel_id]

      attributes
    end
  end
end
