alias Firehose.Test.FakeBlog

defmodule FirehoseWeb.EditorDashboardLiveTest do
  use FirehoseWeb.ConnCase, async: true

  import Phoenix.LiveViewTest

  setup do
    posts = [
      %Blogex.Post{
        id: "live-post",
        title: "Live Post",
        author: "Test Author",
        body: "<p>Body</p>",
        description: "A live post",
        date: ~D[2020-01-01],
        published: true,
        blog: :test_blog,
        tags: []
      },
      %Blogex.Post{
        id: "draft-post",
        title: "Draft Post",
        author: "Test Author",
        body: "<p>Body</p>",
        description: "A draft post",
        date: ~D[2026-03-12],
        published: false,
        blog: :test_blog,
        tags: []
      },
      %Blogex.Post{
        id: "scheduled-post",
        title: "Scheduled Post",
        author: "Test Author",
        body: "<p>Body</p>",
        description: "A scheduled post",
        date: ~D[2099-06-15],
        published: true,
        blog: :test_blog,
        tags: ["future"]
      }
    ]

    {:ok, _} =
      FakeBlog.start(posts,
        blog_id: :test_blog,
        title: "Test Blog",
        base_path: "/blog/test"
      )

    Application.put_env(:blogex, :blogs, [FakeBlog])
    on_exit(fn -> Application.delete_env(:blogex, :blogs) end)

    :ok
  end

  describe "unauthenticated" do
    test "redirects to login", %{conn: conn} do
      assert {:error, redirect} = live(conn, ~p"/editor/dashboard")
      assert {:redirect, %{to: to}} = redirect
      assert to =~ "/users/log-in"
    end
  end

  describe "authenticated" do
    setup :register_and_log_in_user

    test "renders the dashboard", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/editor/dashboard")
      assert html =~ "Dashboard"
    end

    test "shows draft posts", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/editor/dashboard")
      assert html =~ "Draft Post"
    end

    test "shows scheduled posts with days until live", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/editor/dashboard")
      assert html =~ "Scheduled Post"
      assert html =~ "days"
    end

    test "does not show live posts", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/editor/dashboard")
      refute html =~ "Live Post"
    end

    test "renders with app layout including menu", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/editor/dashboard")
      # Verify the app layout is applied by checking for menu elements
      assert html =~ "Willem&#39;s firehose"
      assert html =~ "Blog"
      assert html =~ "Releases"
      assert html =~ "Contact"
      assert html =~ "Dashboard" # This should be in the menu
    end
  end
end
