defmodule BerrypodWeb.SettingsController do
  @moduledoc """
  No-JS fallback for settings form submissions.

  With JS enabled, the LiveView handles everything. Without JS,
  the forms POST here and we redirect back to the LiveView page.
  """
  use BerrypodWeb, :controller

  alias Berrypod.Settings
  alias Berrypod.Stripe.Setup, as: StripeSetup

  def update_from_address(conn, %{"from_address" => address}) do
    address = String.trim(address)

    if address != "" do
      Settings.put_setting("email_from_address", address)

      conn
      |> put_flash(:info, "From address saved")
      |> redirect(to: ~p"/admin/settings")
    else
      conn
      |> put_flash(:error, "From address can't be blank")
      |> redirect(to: ~p"/admin/settings")
    end
  end

  def update_signing_secret(conn, %{"webhook" => %{"signing_secret" => secret}}) do
    if secret == "" do
      conn
      |> put_flash(:error, "Please enter a signing secret")
      |> redirect(to: ~p"/admin/settings")
    else
      StripeSetup.save_signing_secret(secret)

      conn
      |> put_flash(:info, "Signing secret saved")
      |> redirect(to: ~p"/admin/settings")
    end
  end
end
