class UsersController < ApplicationController
  def create
    user = nil
    User.transaction do
      user = User.create!(inheritance_code: SecureRandom.uuid, role: :guest)
      attach_ip_address!(user)
    end

    render json: { code: user.inheritance_code,
                   user: user.slice(:id, :name, :inheritance_code, :role) },
           status: :created
  end

  def verify
    user = User.find_by(inheritance_code: params[:code])
    return render json: { valid: false } unless user
    return head :forbidden if user.banned?

    attach_ip_address!(user)

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

  def renew
    return head :unauthorized unless current_user

    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 render_unprocessable_entity('名前は必須です．', field: :name) if name.blank?

    if user.update(name:)
      render json: user.slice(:id, :name, :inheritance_code, :role), status: :ok
    else
      render_validation_error user
    end
  end

  private

  def attach_ip_address! user
    ip_bin = IPAddr.new(request.remote_ip).hton
    ip_address = IpAddress.create_or_find_by!(ip_address: ip_bin)

    UserIp.create_or_find_by!(user:, ip_address:)
  end
end
