module Keys
  class ProductsController < Keys::BaseController
    def index
      authorize Product

      @products = []
      unless params[:product_type].present?
        flash[:error] = 'Product type is required'
        return
      end

      @product_type = params[:product_type]

      cursor = ''
      if params[:cursor].present?
        cursor = params[:cursor]
      end

      resp = Product.all(@product_type, cursor, current_user.ldap_login)

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error loading product types'
        return
      end

      @products = resp.body['products']
      @cursor = resp.body['cursor']
      @product = Product.new
    end

    def create
      authorize Product

      @product = Product.new
      permitted = params.require(:keys_product).permit(:product_type, :sku, :description).merge(ldap_login: current_user.ldap_login)
      @product.attributes = permitted

      resp = @product.create

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error creating product'
        return redirect_back
      end

      flash[:success] = 'Successfully created product'

      redirect_back
    end
  end
end