defmodule ToweropsWeb.UserSettingsLiveTest do
  use ToweropsWeb.ConnCase, async: true

  import Phoenix.LiveViewTest
  import Towerops.AccountsFixtures

  alias Towerops.Accounts

  setup :register_and_log_in_user

  describe "User Settings LiveView" do
    test "renders settings page", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/users/settings")
      assert html =~ "Account Settings"
      assert html =~ "Change Email"
      assert html =~ "Save Password"
    end

    test "redirects if user is not logged in" do
      conn = build_conn()
      result = live(conn, ~p"/users/settings")
      assert {:error, {:redirect, %{to: "/users/log-in"}}} = result
    end

    @tag token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
    test "redirects if user is not in sudo mode", %{conn: conn} do
      result = live(conn, ~p"/users/settings")
      assert {:error, {:redirect, %{to: "/users/log-in", flash: %{"error" => error}}}} = result
      assert error == "You must re-authenticate to access this page."
    end
  end

  describe "update password" do
    test "updates the user password", %{conn: conn, user: user} do
      {:ok, view, _html} = live(conn, ~p"/users/settings")

      # Password update redirects to login page
      result =
        view
        |> form("#update_password", %{
          "user" => %{
            "password" => "new valid password",
            "password_confirmation" => "new valid password"
          }
        })
        |> render_submit()

      assert {:error, {:redirect, %{to: "/users/log-in"}}} = result

      # Verify password was actually changed
      assert Accounts.get_user_by_email_and_password(user.email, "new valid password")
    end

    test "does not update password on invalid data", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/users/settings")

      result =
        view
        |> form("#update_password", %{
          "user" => %{
            "password" => "too short",
            "password_confirmation" => "does not match"
          }
        })
        |> render_submit()

      assert result =~ "should be at least 12 character(s)"
      assert result =~ "does not match password"
    end
  end

  describe "update email" do
    @tag :capture_log
    test "updates the user email", %{conn: conn, user: user} do
      {:ok, view, _html} = live(conn, ~p"/users/settings")
      new_email = unique_user_email()

      result =
        view
        |> form("#update_email", %{
          "user" => %{"email" => new_email}
        })
        |> render_submit()

      assert result =~ "A link to confirm your email"

      # Email not changed yet until confirmed
      assert Accounts.get_user_by_email(user.email)
    end

    test "does not update email on invalid data", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/users/settings")

      result =
        view
        |> form("#update_email", %{
          "user" => %{"email" => "with spaces"}
        })
        |> render_submit()

      assert result =~ "must have the @ sign and no spaces"
    end
  end

  describe "mobile sessions" do
    test "shows empty state when no mobile sessions", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/users/settings")
      assert html =~ "No mobile devices registered"
    end

    test "shows mobile sessions list", %{conn: conn, user: user} do
      # Create a mobile session
      {:ok, _session} =
        Towerops.MobileSessions.create_mobile_session(%{
          user_id: user.id,
          device_name: "Test iPhone",
          device_os: "iOS 17",
          app_version: "1.0.0"
        })

      {:ok, _view, html} = live(conn, ~p"/users/settings")
      assert html =~ "Test iPhone"
      assert html =~ "iOS 17"
    end

    test "toggles device alerts", %{conn: conn, user: user} do
      {:ok, session} =
        Towerops.MobileSessions.create_mobile_session(%{
          user_id: user.id,
          device_name: "Test iPhone",
          device_os: "iOS 17",
          app_version: "1.0.0",
          alerts_enabled: true
        })

      {:ok, view, _html} = live(conn, ~p"/users/settings")

      # Toggle alerts off
      html =
        view
        |> element("button[phx-click='toggle_device_alerts'][phx-value-session-id='#{session.id}']")
        |> render_click()

      assert html =~ "Alerts disabled for device"

      # Verify in database
      updated_session = Towerops.MobileSessions.get_session(session.id)
      refute updated_session.alerts_enabled
    end

    test "revokes mobile device", %{conn: conn, user: user} do
      {:ok, session} =
        Towerops.MobileSessions.create_mobile_session(%{
          user_id: user.id,
          device_name: "Test iPhone",
          device_os: "iOS 17",
          app_version: "1.0.0"
        })

      {:ok, view, _html} = live(conn, ~p"/users/settings")

      html =
        view
        |> element("button[phx-click='revoke_mobile_device'][phx-value-session-id='#{session.id}']")
        |> render_click()

      assert html =~ "Mobile device removed successfully"

      # Verify session is gone
      assert is_nil(Towerops.MobileSessions.get_session(session.id))
    end
  end

  describe "confirm email with token" do
    setup %{user: user} do
      email = unique_user_email()

      token =
        extract_user_token(fn url ->
          Accounts.deliver_user_update_email_instructions(%{user | email: email}, user.email, url)
        end)

      %{token: token, email: email}
    end

    test "updates the user email once", %{conn: conn, user: user, token: token, email: email} do
      conn = get(conn, ~p"/users/settings/confirm-email/#{token}")
      assert redirected_to(conn) == ~p"/users/settings"

      assert Phoenix.Flash.get(conn.assigns.flash, :info) =~
               "Email changed successfully"

      refute Accounts.get_user_by_email(user.email)
      assert Accounts.get_user_by_email(email)

      conn = get(conn, ~p"/users/settings/confirm-email/#{token}")

      assert redirected_to(conn) == ~p"/users/settings"

      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
               "Email change link is invalid or it has expired"
    end

    test "does not update email with invalid token", %{conn: conn, user: user} do
      conn = get(conn, ~p"/users/settings/confirm-email/oops")
      assert redirected_to(conn) == ~p"/users/settings"

      assert Phoenix.Flash.get(conn.assigns.flash, :error) =~
               "Email change link is invalid or it has expired"

      assert Accounts.get_user_by_email(user.email)
    end

    test "redirects if user is not logged in", %{token: token} do
      conn = build_conn()
      conn = get(conn, ~p"/users/settings/confirm-email/#{token}")
      assert redirected_to(conn) == ~p"/users/log-in"
    end
  end
end
