defmodule BerrypodWeb.SetupControllerTest do
  use BerrypodWeb.ConnCase, async: true

  import Berrypod.AccountsFixtures

  alias Berrypod.Accounts

  describe "GET /setup/login/:token" do
    test "logs in with a valid token and redirects to /setup", %{conn: conn} do
      user = user_fixture()
      token = Accounts.generate_login_token(user)

      conn = get(conn, ~p"/setup/login/#{token}")

      assert redirected_to(conn) == ~p"/setup"
      assert get_session(conn, :user_token)
    end

    test "redirects to /setup with error for invalid token", %{conn: conn} do
      conn = get(conn, ~p"/setup/login/invalid-token")

      assert redirected_to(conn) == ~p"/setup"
      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "Login failed"
    end

    test "token is consumed after use", %{conn: conn} do
      user = user_fixture()
      token = Accounts.generate_login_token(user)

      # First use succeeds
      conn1 = get(conn, ~p"/setup/login/#{token}")
      assert redirected_to(conn1) == ~p"/setup"

      # Second use fails (token consumed)
      conn2 = get(conn, ~p"/setup/login/#{token}")
      assert redirected_to(conn2) == ~p"/setup"
      assert Phoenix.Flash.get(conn2.assigns.flash, :error) =~ "Login failed"
    end
  end
end
