class SetupController < ApplicationController
  before_action :check_setup_allowed

  def show
    @user = User.new(role: :admin)
  end

  def create
    @user = User.new(user_params)
    @user.role = :admin
    @user.invitation_accepted_at = Time.current

    if @user.save
      SetupState.mark_installed!
      session[:user_id] = @user.id
      redirect_to admin_root_path, notice: "Setup complete! Welcome to Sanasto Wiki."
    else
      render :show, status: :unprocessable_entity
    end
  end

  private

  def check_setup_allowed
    if setup_completed?
      redirect_to root_path, alert: "Setup has already been completed."
    end
  end

  def setup_completed?
    SetupState.installed?
  end

  def user_params
    params.require(:user).permit(:email, :name, :password, :password_confirmation, :primary_language)
  end
end
