defmodule ToweropsWeb.OrgLive.NewTest do
  use ToweropsWeb.ConnCase

  import Phoenix.LiveViewTest

  setup :register_and_log_in_user

  describe "New" do
    test "renders new organization form", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/orgs/new")

      assert html =~ "New Organization"
      assert html =~ "name=\"organization[name]\""
    end

    test "validates organization name", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/orgs/new")

      html =
        view
        |> form("#organization-form", %{organization: %{name: ""}})
        |> render_change()

      assert html =~ "can&#39;t be blank"
    end

    test "creates new organization", %{conn: conn, user: user} do
      {:ok, view, _html} = live(conn, ~p"/orgs/new")

      assert view
             |> form("#organization-form", %{organization: %{name: "Test Organization"}})
             |> render_submit()

      # Get the redirect path
      {path, _flash} = assert_redirect(view)

      # Verify redirected to dashboard after creating organization
      assert path == ~p"/dashboard"

      # Verify organization was created by looking up user's organizations
      orgs = Towerops.Organizations.list_user_organizations(user.id)
      org = Enum.find(orgs, fn o -> o.name == "Test Organization" end)
      assert org
      assert org.name == "Test Organization"

      # Verify user is a member
      membership = Towerops.Organizations.get_membership(org.id, user.id)
      assert membership.role == :owner
    end

    test "shows error when organization name is invalid", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/orgs/new")

      html =
        view
        |> form("#organization-form", %{organization: %{name: ""}})
        |> render_submit()

      assert html =~ "can&#39;t be blank"
    end

    test "shows error when organization name is too long", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/orgs/new")

      long_name = String.duplicate("a", 256)

      html =
        view
        |> form("#organization-form", %{organization: %{name: long_name}})
        |> render_submit()

      assert html =~ "should be at most"
    end

    test "requires authentication", %{} do
      conn = build_conn()
      {:error, redirect} = live(conn, ~p"/orgs/new")

      assert {:redirect, %{to: path}} = redirect
      assert path == ~p"/users/log-in"
    end
  end
end
