module Suppliers
  class ProductVariantsController < Suppliers::ApplicationController
    layout 'tablet'

    # GET /product_variants
    # GET /product_variants.json
    def index
    end

    # GET /product_variants/1
    # GET /product_variants/1.json
    def show
    end

    # GET /product_variants/new
    # GET /product_variants/new.json
    def new
    end

    # GET /product_variants/1/edit
    def edit
    end

    # POST /product_variants
    # POST /product_variants.json
    def create
      @product_variant = ProductVariant.new(product_variant_params)
      @product_variant.supplier = current_supplier
      if @product_variant.save
        render json: @product_variant
      else
        render json: {errors: @product_variant.errors}, status: :unprocessable_entity
      end
    end

    # PUT /product_variants/1
    # PUT /product_variants/1.json
    def update
      @product_variant = ProductVariant.find(params[:id])
      head :unprocessable_entity and return unless product_id = product_variant_params[:product_id]
      product = Product.find(product_id)
      head :forbidden and return unless product.supplier_id == current_supplier.id

      if @product_variant.update_attributes(product_variant_params)
        render json: @product_variant
      else
        render json: {errors: @product_variant.errors}, status: :unprocessable_entity
      end
    end

    # DELETE /product_variants/1
    # DELETE /product_variants/1.json
    def destroy
      #@product_variant = ProductVariant.find_by_supplier_id_and_id!(current_supplier.id, params[:id])
      @product_variant = ProductVariant.find(params[:id])
      @product_variant.destroy
      head :no_content
    end

    private

    def product_variant_params
      params.require(:product_variant).permit(:name, :product_id)
    end
  end
end
