class UsersController < ApplicationController
  def create
    user = User.create!(inheritance_code: SecureRandom.uuid, role: 'guest')
    render json: { code: user.inheritance_code,
                   user: user.slice(:id, :name, :inheritance_code, :role) }
  end

  def verify
    ip_bin = IPAddr.new(request.remote_ip).hton
    ip_address = IpAddress.find_or_create_by!(ip_address: ip_bin)

    user = User.find_by(inheritance_code: params[:code])
    return render json: { valid: false } unless user

    UserIp.find_or_create_by!(user:, ip_address:)

    render json: { valid: true, user: user.slice(:id, :name, :inheritance_code, :role) }
  end

  def renew
    user = current_user
    user.inheritance_code = SecureRandom.uuid
    user.save!
    render json: { code: user.inheritance_code }
  end

  def me
    user = User.find_by(inheritance_code: params[:code])
    return head :not_found unless user

    render json: user.slice(:id, :name, :inheritance_code, :role)
  end

  def update
    user = current_user
    return head :unauthorized if user&.id != params[:id].to_i

    name = params[:name]
    return head :bad_request if name.blank?

    if user.update(name:)
      render json: user.slice(:id, :name, :inheritance_code, :role), status: :created
    else
      render json: user.errors, status: :unprocessable_entity
    end
  end
end
