module PayoutEntities
  class WorkflowsController < PayoutEntities::BaseController
    before_action :authorize_payout_entity
    before_action :set_user, only: [:migrate_legacy_partner_workflow]
    before_action :set_workflow_events, except: [:destroy]
    before_action :set_user_attributes, only: [:show]
    before_action :set_invitation_category, except: [:destroy]
    before_action :set_contract_details, except: [:destroy]

    def show
    end

    def edit
    end

    def update
      options = {ldap_login: current_user.ldap_login}

      @contract_details.attributes = update_params
      if @contract_details.save(params[:invitation_id], options)
        flash[:success] = "Success"
        return redirect_to payout_entities_workflow_path(workflow_id: params[:workflow_id], invitation_id: params[:invitation_id])
      else
        flash.now[:danger] = @contract_details.errors.full_messages.to_sentence
        render :edit
      end
    end

    def destroy
      channel_id = params[:channel_id]

      success = Workflow.restart(channel_id, admin_options)
      if success
        flash[:success] = "Workflow restarted"
      else
        flash[:error] = "Workflow restart failed. Please contact Payments team for assistance."
      end
      redirect_back
    end

    def migrate_legacy_partner_workflow
      unless @user.legacy?
        flash[:error] = "User is not a legacy partner. This tool can only migrate legacy partners."
        return redirect_back
      end

      workflow_events = PayoutEntity.workflow_events_for_channel(@user.id) # list is sorted by timestamp, newest first
      legacy_workflow = workflow_events.first

      options = {ldap_login: current_user.ldap_login}
      success = Workflow.migrate_legacy_workflow(legacy_workflow["workflow_id"], options)

      if success
        flash[:success] = "Partner Migration Successful."
      else
        flash[:error] = "Partner Migration failed. Please contact Payments team for assistance."
      end
      redirect_back
    end

    protected

    def authorize_payout_entity
      authorize PayoutEntity
    end

    def set_workflow_events
      @workflow_events = Workflow.find(params[:workflow_id], admin_options)
    end

    def set_user_attributes
      @user_attributes = Workflow.user_attributes(params[:workflow_id], admin_options)
    end

    def set_invitation_category
      @invitation_category = Workflow.invitation_category(params[:invitation_id], admin_options)
    end

    def set_contract_details
      @contract_details = ContractDetails.find(params[:invitation_id], admin_options)
    end

    def update_params
      params.require(:payout_entities_contract_details)
    end

    def admin_options
      {ldap_login: current_user.ldap_login}
    end
  end
end
