defmodule SimpleshopThemeWeb.AdminLive.SettingsTest do
  use SimpleshopThemeWeb.ConnCase, async: false

  import Phoenix.LiveViewTest
  import SimpleshopTheme.AccountsFixtures

  alias SimpleshopTheme.Settings

  setup do
    user = user_fixture()
    %{user: user}
  end

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

  describe "authenticated - not configured" do
    setup %{conn: conn, user: user} do
      conn = log_in_user(conn, user)
      %{conn: conn}
    end

    test "renders setup form when Stripe is not configured", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/admin/settings")

      assert html =~ "Credentials"
      assert html =~ "Not connected"
      assert html =~ "Connect Stripe"
      assert html =~ "Stripe dashboard"
    end

    test "shows error for empty API key", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/settings")

      html =
        view
        |> form("form", %{stripe: %{api_key: ""}})
        |> render_submit()

      assert html =~ "Please enter your Stripe secret key"
    end
  end

  describe "authenticated - connected (localhost)" do
    setup %{conn: conn, user: user} do
      # Pre-configure a Stripe API key
      Settings.put_secret("stripe_api_key", "sk_test_simulated_key_12345")
      conn = log_in_user(conn, user)
      %{conn: conn}
    end

    test "renders dev mode view with CLI instructions", %{conn: conn} do
      {:ok, _view, html} = live(conn, ~p"/admin/settings")

      assert html =~ "Dev mode"
      assert html =~ "sk_test_•••345"
      assert html =~ "stripe listen"
      assert html =~ "Webhook signing secret"
    end

    test "saves manual signing secret", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/settings")

      html =
        view
        |> form("form", %{webhook: %{signing_secret: "whsec_test_manual_456"}})
        |> render_submit()

      assert html =~ "Webhook signing secret saved"
      assert html =~ "whsec_te•••456"
    end

    test "shows error for empty signing secret", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/settings")

      html =
        view
        |> form("form", %{webhook: %{signing_secret: ""}})
        |> render_submit()

      assert html =~ "Please enter a signing secret"
    end

    test "disconnect clears configuration", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/admin/settings")

      html = render_click(view, "disconnect_stripe")

      assert html =~ "Stripe disconnected"
      assert html =~ "Not connected"
      assert html =~ "Connect Stripe"
      refute Settings.has_secret?("stripe_api_key")
    end
  end
end
