module PayoutEntities
  class ItemsController < PayoutEntities::BaseController
    before_action :set_user, only: [:index, :show]

    def index
      authorize PayoutEntity

      options = {ldap_login: current_user.ldap_login}

      if params[:id].present?
        redirect_to payout_entities_item_path(params[:id])
      elsif @user
        @payout_entities = PayoutEntity.find_all_owned_by_channel(@user.id, options)
        if @payout_entities.empty?
          flash[:error] = "No payout entities found for #{@user.login}"
        end
      end
    end

    def show
      authorize PayoutEntity

      options = {ldap_login: current_user.ldap_login}

      if params[:id].present?
        @payout_entity = PayoutEntity.find(params[:id], options: options)

        if @payout_entity.try(:owner_channel_id)
          @user = Twitch::User.find(@payout_entity.owner_channel_id)
        else
          flash.now[:error] = "Payout entity not found"
        end
      elsif @user
        @payout_entity = PayoutEntity.find(@user.id, options: options, find_by_channel_id: true)
      end

      if @payout_entity
        @payout_type = PayoutEntity.payout_type(@payout_entity.owner_channel_id)
        @workflow_events = PayoutEntity.workflow_events_for_payout_entity(params[:id], options)
        @user_attributes = Workflow.user_attributes_by_channel_id(@payout_entity.owner_channel_id, options)

        @payout_attributions = PayoutEntity.payout_attributions(params[:id], options).map do |a|
          user = Twitch::User.find(a["user_id"])
          if user.nil?
            nil
          else
            attribution = {user: user, attribution: a}
            attribution
          end
        end.compact

        if @workflow_events.present? && @workflow_events.first.present? && @workflow_events.first["invitation_id"].present?
          @contract_details = ContractDetails.find(@workflow_events.first["invitation_id"], options)
        end
      end
    end

    private

    def set_user
      return if params[:channel_input].blank?

      options = PayoutEntity.make_params(params)

      begin
        if options[:channel_id].present?
          @user = Twitch::User.find(options[:channel_id])
        else
          @user = Twitch::User.find_by_login(options[:login])
        end

        if @user.blank?
          flash.now[:error] = "User not found"
        end
      rescue RuntimeError
        flash.now[:error] = "This doesn't look like a valid channel ID!"
      end
    end

  end
end
