module Keys
  class ProductTypesController < Keys::BaseController
    def index
      authorize ProductType

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

      resp = ProductType.all(cursor, current_user.ldap_login)

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

      @product_types = resp.body['product_types']
      @cursor = resp.body['cursor']
      @product_type = ProductType.new
    end

    def create
      authorize ProductType

      @product_type = ProductType.new
      permitted = params.require(:keys_product_type).permit(:product_type, :sns_topic, :description).merge(ldap_login: current_user.ldap_login)
      @product_type.attributes = permitted

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

      flash[:success] = 'Successfully created product type'

      redirect_back
    end
  end
end
