require "test_helper"

class InvitationsControllerTest < ActionDispatch::IntegrationTest
  test "should show invitation acceptance page with valid token" do
    user = users(:pending_invitation)

    get invitation_path(user.invitation_token)

    assert_response :success
    assert_select "h1", "Accept Invitation"
    assert_select "input[type=password]", count: 2
  end

  test "should redirect with invalid token" do
    get invitation_path("invalid_token")

    assert_redirected_to root_path
    assert_equal "Invalid or expired invitation link.", flash[:alert]
  end

  test "should redirect with expired token" do
    user = users(:pending_invitation)
    user.update(invitation_sent_at: 15.days.ago)

    get invitation_path(user.invitation_token)

    assert_redirected_to root_path
    assert_equal "Invalid or expired invitation link.", flash[:alert]
  end

  test "should accept invitation with valid password" do
    user = users(:pending_invitation)

    patch accept_invitation_path(user.invitation_token), params: {
      user: {
        password: "securepassword123",
        password_confirmation: "securepassword123"
      }
    }

    user.reload
    assert_not_nil user.invitation_accepted_at
    assert_nil user.invitation_token
    assert_equal user.id, session[:user_id]
    assert_redirected_to root_path
  end

  test "should not accept invitation with short password" do
    user = users(:pending_invitation)

    patch accept_invitation_path(user.invitation_token), params: {
      user: {
        password: "short",
        password_confirmation: "short"
      }
    }

    user.reload
    assert_nil user.invitation_accepted_at
    assert_not_nil user.invitation_token
    assert_response :unprocessable_entity
  end

  test "should not accept invitation with mismatched passwords" do
    user = users(:pending_invitation)

    patch accept_invitation_path(user.invitation_token), params: {
      user: {
        password: "securepassword123",
        password_confirmation: "differentpassword"
      }
    }

    user.reload
    assert_nil user.invitation_accepted_at
    assert_response :unprocessable_entity
  end

  test "should not accept expired invitation" do
    user = users(:pending_invitation)
    user.update(invitation_sent_at: 15.days.ago)

    patch accept_invitation_path(user.invitation_token), params: {
      user: {
        password: "securepassword123",
        password_confirmation: "securepassword123"
      }
    }

    assert_redirected_to root_path
    assert_equal "Invalid or expired invitation link.", flash[:alert]
  end
end
