require "test_helper"

class SetupControllerTest < ActionDispatch::IntegrationTest
  def setup
    SetupState.reset!
  end

  def teardown
    SetupState.reset!
  end

  test "should show setup page when not installed" do
    get setup_path
    assert_response :success
    assert_select "h2", /Create Admin Account/
  end

  test "should redirect to root when already installed" do
    SetupState.mark_installed!

    get setup_path
    assert_redirected_to root_path
    assert_equal "Setup has already been completed.", flash[:alert]
  end

  test "should create admin user and mark as installed" do
    assert_difference("User.count", 1) do
      post setup_path, params: {
        user: {
          email: "setupadmin@example.com",
          name: "Setup Admin",
          password: "securepassword123",
          password_confirmation: "securepassword123",
          primary_language: "en"
        }
      }
    end

    assert SetupState.installed?

    new_user = User.find_by(email: "setupadmin@example.com")
    assert_not_nil new_user
    assert_equal "admin", new_user.role
    assert_not_nil new_user.invitation_accepted_at
    assert_equal new_user.id, session[:user_id]

    assert_redirected_to admin_root_path
  end

  test "should not create user with invalid password" do
    assert_no_difference("User.count") do
      post setup_path, params: {
        user: {
          email: "setupadmin@example.com",
          name: "Setup Admin",
          password: "short",  # Too short, minimum is 12
          password_confirmation: "short",
          primary_language: "en"
        }
      }
    end

    assert_not SetupState.installed?
    assert_response :unprocessable_entity
  end

  test "should not create user with mismatched passwords" do
    assert_no_difference("User.count") do
      post setup_path, params: {
        user: {
          email: "setupadmin@example.com",
          name: "Setup Admin",
          password: "securepassword123",
          password_confirmation: "differentpassword",
          primary_language: "en"
        }
      }
    end

    assert_not SetupState.installed?
    assert_response :unprocessable_entity
  end

  test "should not create user without email" do
    assert_no_difference("User.count") do
      post setup_path, params: {
        user: {
          email: "",
          name: "Setup Admin",
          password: "securepassword123",
          password_confirmation: "securepassword123",
          primary_language: "en"
        }
      }
    end

    assert_not SetupState.installed?
    assert_response :unprocessable_entity
  end
end
