module Dunlop::WorkflowInstanceModel::CategorizationAndResetHandling
  extend ActiveSupport::Concern

  # Reset the attributes defined on the collection to the default value of a new record
  # and set the state back to unplanned and activate the special_care_flag
  def reset!
    workflow_steps.each(&:reset!)
    new_record = self.class.new
    collection_class.attributes.except('notes').each do |attr, _collection_value|
      self[attr] = new_record[attr]
    end
    unplanned
  end

  # change the scenario
  def categorize_as(scenario_name)
    scenario_name = scenario_name.to_sym
    new_scenario_class = "WorkflowInstance::#{scenario_name.to_s.classify}".constantize
    return if self.class == new_scenario_class

    # remove obsolete
    obsolete_workflow_steps = (self.class.scenario_workflow_step_names - new_scenario_class.scenario_workflow_step_names).map(&:to_s)
    workflow_steps.select{|ws| obsolete_workflow_steps.include? ws.process_name}.each(&:destroy)

    extra_workflow_steps = (new_scenario_class.scenario_workflow_step_names - self.class.scenario_workflow_step_names).map(&:to_s)
    _overlap_workflow_steps = (new_scenario_class.scenario_workflow_step_names & self.class.scenario_workflow_step_names).map(&:to_s)

    # transform
    target = becomes(new_scenario_class)
    target.sti_type = new_scenario_class.name

    # add missing steps
    extra_workflow_steps.each{|ws| target.public_send "build_#{ws}", sti_type: "#{ws.classify}::#{scenario_name.to_s.classify}"}

    target.save and target
  end
end
