module Ads
  class RevenueConfigsController < ApplicationController
    before_action :set_user, only: [:new]
    before_action :check_auth

    def new
      @revenue_config = Ads::RevenueConfig.new
      @today = Date.current
    end

    def create
      @revenue_config = Ads::RevenueConfig.new(create_params)
      if @revenue_config.save
        flash[:success] = "Success"
      else
        flash[:error] = "Error updating revenue_config: #{@revenue_config.errors.full_messages.to_sentence}"
      end
      redirect_to twitch_user_path(@revenue_config.user_id)
    end

    def new_bulk
      new
    end

    def create_bulk
      @revenue_config = Ads::RevenueConfig.new(create_params)
      @revenue_config.user_id = @revenue_config.user_id.split
      if @revenue_config.save
        flash[:success] = "Success"
      else
        flash[:error] = "Error updating revenue_config: #{@revenue_config.errors.full_messages.to_sentence}"
      end
      redirect_to new_bulk_ads_revenue_configs_path
    end

    def create_params
      params.require(:ads_revenue_config)
    end

    def destroy
      config = Ads::RevenueConfig.new id: params[:id]
      if config.destroy
        flash[:success] = "Success: config deleted"
      else
        flash[:error] = "Error deleting revenue_config: #{config.errors.full_messages.to_sentence}"
      end
      redirect_back
    end

    private

    def check_auth
      authorize Ads::RevenueConfig
    end

    def set_user
      user_id = params[:user_id]
      @user = Twitch::User.find(user_id.to_i)
    end
  end
end
