class GameSetupService
  def initialize(game, client: GameApiClient.new)
    @game = game
    @client = client
  end

  def setup_initial_turn
    initial_response = @client.api_game_initial_state

    unless initial_response && initial_response["game_state"]
        return { success: false, message: "初期状態の取得に失敗しました。" }
    end

    initial_state = initial_response["game_state"]
    svg_render = @client.api_render(initial_state)
    possible_orders = @client.api_calculate_possible_orders(initial_state, by_power: true)

    @game.turns.build(
      number: 1,
      game_state: initial_state,
      possible_orders: possible_orders,
      phase: initial_state&.dig("name"),
      svg_date: svg_render,
      # Initialize svg_orders with NONE (and standard rendering as default)
      svg_orders: { "NONE" => svg_render }
    )

    if @game.save
      { success: true, message: "ゲームが初期化されました。" }
    else
      { success: false, message: "初期ターンの作成に失敗しました: #{@game.errors.full_messages.join(', ')}" }
    end
  rescue StandardError => e
    Rails.logger.error("Game setup failed: #{e.message}")
    { success: false, message: "予期せぬエラーが発生しました。" }
  end
end
