require 'rails_helper'

describe WorkflowInstance do

  let(:time) { '2016-12-24T04:22:00Z'.to_time }
  let(:user) { build :user }
  before do
    Timecop.freeze time
    User.current = user
  end
  after { Timecop.return }

  describe '#reset!' do
    it "sunny" do
      batch = create :workflow_instance_batch_scenario1
      wi = build :workflow_instance_scenario1, :active, my_name: 'Hi My Name is', zipcode: '1234AB', bucket: 'Edited bucket'
      wi.workflow_instance_batch = batch
      wi.owner_initialization.assign_attributes(
        window_from: 4,
        notes: 'QED'
      )
      wi.save

      wi.reset!

      reload_model wi

      wi.my_name.should eq 'Hi My Name is' # non editable attributes are not reset!
      wi.zipcode.should eq '1234AB'
      wi.bucket.should be_blank
      wi.workflow_instance_batch.should be_blank
      wi.should be_unplanned

      wi.owner_initialization.window_from.should be_blank
      wi.owner_initialization.notes.should eq <<-NOTES.strip_heredoc.strip
       2016-12-24T07:22:00+03:00 #{user.email}
       QED

       2016-12-24T07:22:00+03:00 #{user.email}
       [RESET]
       [CHANGE] Window from changed to [EMPTY]
       [STATE_CHANGE] processing => pending
      NOTES
      wi.owner_initialization.should be_pending
    end

  end

  describe "#categorize_as" do
    it "works from base WorkflowInstance with symbol" do
      wi = create :workflow_instance, bucket: 'Hi there'
      wi.class.should eq WorkflowInstance
      wi.workflow_steps.should be_empty

      categorized = wi.categorize_as :scenario1
      categorized.reload
      categorized.class.should eq WorkflowInstance::Scenario1
      categorized.workflow_steps.map(&:class).map(&:name).should eq %w[OwnerInitialization::Scenario1 ContractorInitialization::Scenario1]
    end

    it "works from base WorkflowInstance with string" do
      wi = create :workflow_instance, bucket: 'Hi there'
      wi.class.should eq WorkflowInstance
      wi.workflow_steps.should be_empty

      categorized = wi.categorize_as 'scenario1'
      categorized.reload
      categorized.class.should eq WorkflowInstance::Scenario1
      categorized.workflow_steps.map(&:class).map(&:name).should eq %w[OwnerInitialization::Scenario1 ContractorInitialization::Scenario1]
    end

    it "works from one scenario to another" do
      wi = create :workflow_instance_scenario1, bucket: 'Hi there', contractor_initialization: build(:contractor_initialization_scenario1, replace_notes: "My notes\n\n")
      categorized = wi.categorize_as :scenario2
      categorized.reload
      categorized.class.should eq WorkflowInstance::Scenario2
      categorized.workflow_steps.map(&:process_name).should eq %w[contractor_initialization wba_submission]
      categorized.contractor_initialization.notes.should eq "My notes\n\n" # preserved
    end
  end
end
