class ParticipantsController < ApplicationController
  before_action :set_game

  # POST /games/:game_id/participants
  def create
    # パスワード確認
    if @game.password_protected?
      unless @game.authenticate_password(params[:password])
        redirect_to @game, alert: "パスワードが正しくありません"
        return
      end
    end

    # 参加処理
    @participant = @game.participants.build(
      user: current_user,
      is_administrator: false
    )

    if @participant.save
      # 定員到達チェック
      if @game.participants.count == @game.participants_count
        @game.update(status: "power_selection")
      end

      redirect_to @game, notice: "ゲームに参加しました"
    else
      redirect_to @game, alert: @participant.errors.full_messages.join(", ")
    end
  end

  # PATCH /games/:game_id/participants/:id/select_power
  def select_power
    @participant = @game.participants.find(params[:id])

    unless @participant.user == current_user
      redirect_to @game, alert: "権限がありません"
      return
    end

    if @participant.update(power: params[:power])
      # 全員が国を選択したかチェック
      if @game.all_powers_assigned?
        service = GameSetupService.new(@game)
        result = service.setup_initial_turn

        if result[:success]
          @game.update(status: "in_progress")
          flash[:notice] = "国を選択し、ゲームが開始されました！"
        else
          flash[:alert] = "ゲーム開始に失敗しました: #{result[:message]}"
        end
      else
        flash[:notice] = "国を選択しました"
      end

      redirect_to @game
    else
      redirect_to @game, alert: @participant.errors.full_messages.join(", ")
    end
  end

  # DELETE /games/:game_id/participants/:id
  def destroy
    @participant = @game.participants.find(params[:id])

    unless @participant.user == current_user || current_user&.admin?
      redirect_to @game, alert: "権限がありません"
      return
    end

    @participant.destroy

    # ゲーム状態を更新
    if @game.status == "power_selection"
      @game.update(status: "recruiting")
    end

    redirect_to games_path, notice: "ゲームから退出しました"
  end

  private

  def set_game
    @game = Game.find(params[:game_id])
  end
end
