module Dmca
  class UsersController < Dmca::BaseController
    before_action :set_user, only: [:show, :destroy]

    def index
      authorize User
      @user = nil
      begin
        @user = User.find(params[:user][:id]) if params[:user].present? && params[:user][:id].present?
      rescue StandardError => e
        flash.now[:danger] = e
      end
    end

    def show
    end

    def new
      @user = User.new
      authorize @user
    end

    def create
      @user = User.new user_params
      authorize @user

      if @user.save
        flash[:success] = "Success"
        redirect_to dmca_users_path
      else
        flash.now[:danger] = @user.errors.full_messages.to_sentence
        render :new
      end
    end

    def destroy
      if @user.destroy
        flash[:success] = "Success"
      else
        flash[:error] = @user.errors.full_messages.to_sentence
      end

      redirect_back
    end

    protected

    def set_user
      @user = User.find params[:id]
      authorize @user
    end

    def user_params
      params.require(:dmca_user).permit(:user_id, :company, :email, :phone_number, :address)
    end
  end
end
