require "test_helper"

class BoardsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @game = games(:one)
    # fixtureのgames(:one)はtitleだけの状態から修正されている前提だが、
    # 念のためupdateして整合性を取る
    @game.update!(
      status: "in_progress",
      participants_count: 7,
      victory_sc_count: 18,
      scoring_system: "none",
      turn_schedule: "0,12"
    )

    @user = users(:austria)
    @user_germany = users(:germany)

    # 参加者作成
    # BoardTest同様、fixtureに依存せずParticipantを作る
    @p_austria = Participant.create!(game: @game, user: @user, power: "AUSTRIA")
    @p_germany = Participant.create!(game: @game, user: @user_germany, power: "GERMANY")

    # 共通掲示板作成
    @game.boards.create!(board_type: "global", is_public: true)
  end

  test "should get index" do
    login_as(@user)
    get game_boards_url(@game)
    assert_response :success
    assert_select "h2", "外交・交渉掲示板"
  end

  test "should get new negotiation board" do
    login_as(@user)
    get new_game_board_url(@game)
    assert_response :success
  end

  test "should create negotiation board" do
    login_as(@user)
    assert_difference("Board.count") do
      post game_boards_url(@game), params: {
        invited_participant_ids: [ @p_germany.id ]
      }
    end

    assert_redirected_to game_board_url(@game, Board.last)
    assert Board.last.member?(@p_austria)
    assert Board.last.member?(@p_germany)
  end

  test "should show board" do
    login_as(@user)
    board = @game.boards.global.first
    get game_board_url(@game, board)
    assert_response :success
  end

  test "should not show board to non-member" do
    # 第三者作成
    user_russia = users(:russia)
    p_russia = Participant.create!(game: @game, user: user_russia, power: "RUSSIA")

    # オーストリアとドイツの掲示板
    board = @game.boards.create!(board_type: "negotiation", created_by_participant_id: @p_austria.id)
    board.board_memberships.create!(participant: @p_austria, joined_at: Time.current)
    board.board_memberships.create!(participant: @p_germany, joined_at: Time.current)

    # ロシアでログイン
    login_as(user_russia)
    get game_board_url(@game, board)

    assert_redirected_to game_boards_url(@game)
    follow_redirect!
    assert_select "div[role='alert']", /権限がありません/
  end
end
