# frozen_string_literal: true

class Admin::ProductsController < Admin::ApplicationController
  def index
    @pagy, @products = pagy(
      Product.order(ord: :desc),
      items: 20
    )
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.update(user: current_user)
      flash[:success] = "Created successfully"
      redirect_to action: :index
    else
      render :new
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
      flash[:success] = "Updated successfully"
      redirect_to action: :index
    else
      render :edit
    end
  end

  def destroy
    @product = Product.find(params[:id])
    if @product.update(deleted_at: Time.now)
      flash[:success] = "Destroyed successfully"
      redirect_to action: :index
    else
      flash[:error] = "Destroyed failed: #{@product.short_error_message}"
      redirect_to action: :index
    end
  end

  def restore
    @product = Product.find(params[:id])
    if @product.update(deleted_at: nil)
      flash[:success] = "Restore successfully"
      redirect_to action: :index
    else
      flash[:error] = "Restore failed: #{@product.short_error_message}"
      redirect_to action: :index
    end
  end

  private

    def product_params
      params.require(:product).permit(:ord, :name)
    end
end
