defmodule BerrypodWeb.EmailSettingsController do
  @moduledoc """
  No-JS fallback for email settings form submission.

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

  alias Berrypod.Mailer

  def update(conn, %{"email" => params}) do
    adapter_key = params["adapter"]
    # Fields are namespaced: email[brevo][api_key] → params["brevo"]["api_key"]
    adapter_params = params[adapter_key] || %{}

    case Mailer.save_config(adapter_key, adapter_params, conn.assigns.current_scope.user.email) do
      {:ok, _adapter_info} ->
        conn
        |> put_flash(:info, "Settings saved — send a test email to check it works")
        |> redirect(to: ~p"/admin/settings/email")

      {:error, field_errors} when is_map(field_errors) ->
        conn
        |> put_flash(:field_errors, field_errors)
        |> put_flash(:error_adapter, adapter_key)
        |> redirect(to: ~p"/admin/settings/email")
    end
  end

  def test(conn, _params) do
    user = conn.assigns.current_scope.user

    case Mailer.send_test_email(user.email, Mailer.from_address()) do
      {:ok, _} ->
        Mailer.mark_email_verified()

        conn
        |> put_flash(:info, "Test email sent to #{user.email}")
        |> redirect(to: ~p"/admin/settings/email")

      {:error, reason} ->
        conn
        |> put_flash(:error, Mailer.friendly_error(reason))
        |> redirect(to: ~p"/admin/settings/email")
    end
  end
end
