# frozen_string_literal: true

class Admin::ComponentsController < Admin::ApplicationController
  def index
    @pagy, @components = pagy(
      Component.order(ord: :desc),
      items: 20
    )
  end

  def new
    @component = Component.new
  end

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

  def edit
    @component = Component.find(params[:id])
  end

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

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

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

  private

    def component_params
      params.require(:component).permit(:ord, :name)
    end
end
