class Master::Api::ProvidersController < Master::Api::BaseController

  # Change the partner of a provider account
  #
  # Params:
  # - application_plan: system_name should be valid for the partneter
  # - partner: system_name, could be nil
  # - api_key: API KEY of master account
  #
  # Description:
  #
  # Allow set or unset a partner for a provider account.
  # Could be used to move heroku providers to normal application plans
  # and move to heroku again.
  #
  # For heroku accounts we save some data in account.settings, this data
  # is not deleted.
  #
  # You should not move normal providers to heroku accounts because need
  # some special data that is provider for heroku when create an account.
  def change_partner
    get_provider
    get_partner
    get_application_plan
    @provider.partner = @partner # could be nil
    @provider.save
    @provider.force_upgrade_to_provider_plan!(@application_plan)
    render json: @provider.as_json(include: [:bought_cinstance, :partner])
  end

  private

  def get_partner
    @partner = Partner.find_by_system_name(params[:partner])
  end

  def get_application_plan
    application_plans = Account.master.application_plans.where(partner_id: @partner.try!(:id))
    @application_plan = application_plans.find_by_system_name(params[:application_plan])
    raise ActiveRecord::RecordNotFound if @application_plan.blank?
  end

  def get_provider
    @provider = Account.providers.find(params[:id])
  end
end
