class BoardProposalsController < ApplicationController
  include BoardAccessible

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

  def create
    unless @board.member?(@current_participant)
      return redirect_to game_board_path(@game, @board), alert: "権限がありません"
    end

    @proposal = @board.board_proposals.new(proposal_params)
    @proposal.proposer = @current_participant
    @proposal.status = "pending"

    # フェーズ情報の保存（latest_turnアソシエーションを使用）
    latest_turn = @game.latest_turn
    @proposal.phase = latest_turn&.phase || "S1901M"

    if @proposal.save
      redirect_to game_board_path(@game, @board), notice: "提案を作成しました"
    else
      redirect_to game_board_path(@game, @board), alert: "提案の作成に失敗しました"
    end
  end

  def update
    @proposal = @board.board_proposals.find(params[:id])

    unless @board.member?(@current_participant)
      return redirect_to game_board_path(@game, @board), alert: "権限がありません"
    end

    new_status = params[:board_proposal][:status]
    if %w[accepted rejected].include?(new_status)
      @proposal.update!(status: new_status)
      redirect_to game_board_path(@game, @board), notice: "提案を#{new_status == 'accepted' ? '承認' : '拒否'}しました"
    else
      redirect_to game_board_path(@game, @board), alert: "不正なステータスです"
    end
  end

  private

  def proposal_params
    params.require(:board_proposal).permit(:body)
  end
end
