class BoardMembershipsController < ApplicationController
  include BoardAccessible

  before_action :require_login
  before_action :set_game
  before_action :set_board
  before_action :set_current_participant

  def create
    # メンバー追加処理
    unless @board.negotiation? && @board.member?(@current_participant)
      return redirect_to game_board_path(@game, @board), alert: "権限がありません"
    end

    target_participant_id = params[:participant_id]

    # 重複チェック（既に参加しているか）
    if @board.board_memberships.where(participant_id: target_participant_id, left_at: nil).exists?
      return redirect_to game_board_path(@game, @board), alert: "そのプレイヤーは既に参加しています"
    end

    # 退出済みの場合は再参加（left_atをクリア）
    membership = @board.board_memberships.find_by(participant_id: target_participant_id)
    if membership
      membership.update!(left_at: nil, joined_at: Time.current)
    else
      @board.board_memberships.create!(participant_id: target_participant_id, joined_at: Time.current)
    end

    redirect_to game_board_path(@game, @board), notice: "メンバーを追加しました"
  rescue ActiveRecord::RecordInvalid => e
    redirect_to game_board_path(@game, @board), alert: "メンバー追加に失敗しました: #{e.message}"
  end

  def leave
    # 退出処理
    unless @board.negotiation? && @board.member?(@current_participant)
      return redirect_to game_board_path(@game, @board), alert: "退出できません"
    end

    membership = @board.board_memberships.find_by(participant: @current_participant)
    if membership
      membership.leave!
      redirect_to game_boards_path(@game), notice: "掲示板から退出しました"
    else
      redirect_to game_board_path(@game, @board), alert: "退出に失敗しました"
    end
  end
end
