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

  alias MatchmakingEx.Server
  alias MatchmakingEx.Player
  alias MatchmakingEx.CooldownManager

  # Start the necessary servers for each test.
  setup do
    start_supervised!(Server)
    start_supervised!(CooldownManager)
    :ok
  end

  @doc """
  Tests that a player is added to the queue if no compatible opponent is present.
  """
  test "adds a player to the queue when no compatible opponents exist" do
    # Start a player process to interact with the server.
    start_supervised!({Player, "player1"})
    Player.search("player1", %{rank: "gold"})

    # To verify, we try to find this player with another one.
    start_supervised!({Player, "finder"})
    Player.search("finder", %{rank: "gold"})

    assert_receive {:match_ready_for_confirmation, _match_id, players}, 500
    assert "player1" in players and "finder" in players
  end

  @doc """
  Tests that a pending match is created when a compatible opponent is found.
  """
  test "creates a pending match when a compatible opponent is found" do
    start_supervised!({Player, "player1"})
    start_supervised!({Player, "player2"})

    Player.search("player1", %{rank: "gold"})
    Player.search("player2", %{rank: "gold"})

    assert_receive {:match_ready_for_confirmation, _match_id, players}, 500
    assert "player1" in players and "player2" in players
  end
end
