defmodule BerrypodWeb.ProvidersController do
  @moduledoc """
  No-JS fallback for provider connection forms.

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

  alias Berrypod.{KeyValidation, Products}
  alias Berrypod.Providers.Provider

  def create(conn, %{"provider_connection" => params}) do
    api_key = params["api_key"]
    provider_type = params["provider_type"]
    provider = Provider.get(provider_type)

    case KeyValidation.validate_provider_key(api_key, provider_type) do
      {:error, message} ->
        conn
        |> put_flash(:error, message)
        |> redirect(to: ~p"/admin/providers/new?type=#{provider_type}")

      {:ok, api_key} ->
        case Products.connect_provider(api_key, provider_type) do
          {:ok, _connection} ->
            conn
            |> put_flash(:info, "Connected to #{provider.name}!")
            |> redirect(to: ~p"/admin/settings")

          {:error, _reason} ->
            conn
            |> put_flash(:error, "Could not connect. Check your API key and try again")
            |> redirect(to: ~p"/admin/providers/new?type=#{provider_type}")
        end
    end
  end

  def update(conn, %{"id" => id, "provider_connection" => params}) do
    connection = Products.get_provider_connection!(id)

    case Products.update_provider_connection(connection, params) do
      {:ok, _connection} ->
        conn
        |> put_flash(:info, "Settings saved")
        |> redirect(to: ~p"/admin/settings")

      {:error, _changeset} ->
        conn
        |> put_flash(:error, "Could not save settings")
        |> redirect(to: ~p"/admin/providers/#{id}/edit")
    end
  end
end
