defmodule MatchmakingEx.PlayerTest do
  @moduledoc false
  use ExUnit.Case, async: true

  alias MatchmakingEx.Player

  # Sets up a unique player process for each test.
  setup do
    player_name = "player_#{System.unique_integer([:positive])}"
    start_supervised!({Player, player_name})
    {:ok, player_name: player_name}
  end

  @doc """
  Verifies that a new player process starts with the correct initial state.
  """
  test "starts with the correct initial state", %{player_name: name} do
    {:ok, state} = GenServer.call({:via, Registry, {MatchmakingEx.Registry, name}}, :get_state)
    assert state.id == name
    assert state.current_match_id == nil
  end

  @doc """
  Verifies that the player's state is updated correctly when a match is found.
  """
  test "updates state when receiving a pending confirmation", %{player_name: name} do
    [{player_pid, _}] = Registry.lookup(MatchmakingEx.Registry, name)
    send(player_pid, {:match_ready_for_confirmation, "match1", ["p1", "p2"]})

    :timer.sleep(10)
    {:ok, state} = GenServer.call({:via, Registry, {MatchmakingEx.Registry, name}}, :get_state)
    assert state.current_match_id == "match1"
  end
end
