class QuotationsController < ApplicationController
  before_action :set_products, :set_user, only: :create

  def new
    @user = User.new
  end

  def products_step
    @user = User.new user_params

    if @user.save
      @product = Product.new
    else
      render :new
    end
  end

  def create
    @product.assign_attributes(product_params_by_type)

    if @product.save
      @user.products << @product
      # Creates a Quotation and redirects from here
    else
      render :products_step
    end
  end

  def show
  end

  private

    def set_products
      raise 'Invalid product type' unless Product.types.values.include?(product_type)
      @product = product_type.constantize.new
    end

    def set_user
      @user = User.find(params[:user_id])
    end

    def product_params_by_type
      case product_type
      when Product.types[:subscription]
        params.require(:product).permit(:start_date, :end_date, :price_per_day)
      else
        # ...
      end
    end

    def product_type
      params.require(:product).permit(:product_type).dig(:product_type)
    end

    def user_params
      params.require(:user).permit(:name, :password, :email, :phone)
    end
end
