defmodule BerrypodWeb.Shop.ComingSoonTest do
  use BerrypodWeb.ConnCase, async: false

  import Phoenix.LiveViewTest
  import Berrypod.AccountsFixtures

  alias Berrypod.Settings

  describe "coming soon page" do
    test "renders when site is not live and admin exists", %{conn: conn} do
      user_fixture()

      {:ok, _view, html} = live(conn, ~p"/coming-soon")

      assert html =~ "Coming soon"
      assert html =~ "getting things ready"
    end

    test "displays the shop name", %{conn: conn} do
      user_fixture()
      Settings.put_setting("site_name", "My Test Shop", "string")

      {:ok, _view, html} = live(conn, ~p"/coming-soon")

      assert html =~ "My Test Shop"
    end
  end

  describe "site live gate" do
    test "redirects unauthenticated visitors to coming soon when not live", %{conn: conn} do
      # Create admin so the gate activates (fresh installs bypass)
      user_fixture()

      assert {:error, {:redirect, %{to: "/coming-soon"}}} = live(conn, ~p"/")
    end

    test "allows authenticated admin through when not live", %{conn: conn} do
      user = user_fixture()
      conn = log_in_user(conn, user)

      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ "Shop the collection"
    end

    test "allows everyone through when site is live", %{conn: conn} do
      user_fixture()
      {:ok, _} = Settings.set_site_live(true)

      {:ok, _view, html} = live(conn, ~p"/")

      assert html =~ "Shop the collection"
    end

    test "redirects to setup on fresh install (no admin)", %{conn: conn} do
      # No admin created — redirect to setup
      assert {:error, {:redirect, %{to: "/setup"}}} = live(conn, ~p"/")
    end

    test "redirects when session token is stale (user deleted)", %{conn: conn} do
      user = user_fixture()
      conn = log_in_user(conn, user)

      # Delete the user — session cookie is now stale
      Berrypod.Repo.delete!(user)

      assert {:error, {:redirect, %{to: "/setup"}}} = live(conn, ~p"/")
    end

    test "gates all public shop routes", %{conn: conn} do
      user_fixture()

      assert {:error, {:redirect, %{to: "/coming-soon"}}} = live(conn, ~p"/about")
      assert {:error, {:redirect, %{to: "/coming-soon"}}} = live(conn, ~p"/collections/all")
      assert {:error, {:redirect, %{to: "/coming-soon"}}} = live(conn, ~p"/cart")
    end
  end
end
