ENV["RAILS_ENV"] ||= "test"
require_relative "../test/test_helper"

class RefactoringVerificationTest < ActiveSupport::TestCase
  def setup
    @game = Game.create!(title: "Refactor Test #{Time.now.to_r}", status: "recruiting", participants_count: 7, is_solo_mode: true)
  end

  # Mock Client Class
  class MockClient
    def initialize(initial_state: {}, possible_orders: {}, render_result: "<svg>...</svg>", process_result: nil, auto_orders: nil)
      @initial_state = initial_state
      @possible_orders = possible_orders
      @render_result = render_result
      @process_result = process_result
      @auto_orders = auto_orders
    end

    def api_game_initial_state(map_name = "standard")
      @initial_state
    end

    def api_render(game_state, orders: nil, incl_orders: true, incl_abbrev: true)
      @render_result
    end

    def api_calculate_possible_orders(game_state, power_name: "", by_power: false)
      @possible_orders
    end

    def api_calculate_process(game_state, orders)
      @process_result
    end

    def api_calculate_auto_orders(game_state, power_name)
      @auto_orders
    end
  end

  test "GameSetupService creates initial turn" do
    mock_client = MockClient.new(
      initial_state: { "game_state" => { "name" => "Spring 1901" } },
      possible_orders: { "FRANCE" => [] }
    )

    service = GameSetupService.new(@game, client: mock_client)
    result = service.setup_initial_turn

    assert result[:success], "Service failed: #{result[:message]}"
    assert_equal 1, @game.turns.count
    assert_equal "Spring 1901", @game.turns.first.phase
  end

  test "OrderSubmissionService submits orders" do
    turn = @game.turns.create!(number: 1, game_state: { "name" => "S1901" })
    user = User.create!(username: "TestUser#{Time.now.to_r}", email: "test#{Time.now.to_r}@example.com", password: "password")

    mock_client = MockClient.new

    service = OrderSubmissionService.new(turn, user, client: mock_client)
    orders = { "A PAR" => "H" }

    result = service.submit(power: "FRANCE", orders: orders)

    assert result[:success]
    turn.reload
    assert_equal "H", turn.orders["FRANCE"]["A PAR"]
  end

  test "TurnProcessingService processes turn" do
    turn = @game.turns.create!(number: 1, game_state: { "name" => "S1901" })

    mock_client = MockClient.new(
      process_result: { "game_state" => { "name" => "Fall 1901" } },
      possible_orders: {}
    )

    service = TurnProcessingService.new(turn, client: mock_client)
    result = service.process(force: "true")

    assert result[:success], result[:message]
    assert_equal 2, @game.turns.count
    assert_equal "Fall 1901", @game.turns.last.phase
  end
end
