defmodule Berrypod.Mailer.AdaptersTest do
  use ExUnit.Case, async: true

  alias Berrypod.Mailer.Adapters

  describe "all/0" do
    test "returns a list of adapters" do
      adapters = Adapters.all()
      assert is_list(adapters)
      assert length(adapters) >= 5
    end

    test "each adapter has required keys" do
      for adapter <- Adapters.all() do
        assert is_binary(adapter.key)
        assert is_binary(adapter.name)
        assert is_atom(adapter.module)
        assert is_binary(adapter.description)
        assert is_list(adapter.fields)
        assert length(adapter.fields) >= 1
      end
    end

    test "each adapter has a url (or nil for SMTP)" do
      for adapter <- Adapters.all() do
        if adapter.key == "smtp" do
          assert is_nil(adapter.url)
        else
          assert is_binary(adapter.url)
        end
      end
    end

    test "each field has required keys" do
      for adapter <- Adapters.all(), field <- adapter.fields do
        assert is_binary(field.key)
        assert is_binary(field.label)
        assert field.type in [:string, :integer, :secret]
      end
    end
  end

  describe "get/1" do
    test "returns adapter by key" do
      assert %{key: "smtp", name: "SMTP"} = Adapters.get("smtp")
      assert %{key: "mailjet", name: "Mailjet"} = Adapters.get("mailjet")
      assert %{key: "postal", name: "Postal"} = Adapters.get("postal")
      assert is_nil(Adapters.get("postmark"))
      assert is_nil(Adapters.get("mailpace"))
    end

    test "returns nil for unknown key" do
      assert is_nil(Adapters.get("unknown"))
    end
  end

  describe "field_keys/1" do
    test "returns namespaced settings keys" do
      smtp = Adapters.get("smtp")
      keys = Adapters.field_keys(smtp)

      assert "email_smtp_relay" in keys
      assert "email_smtp_port" in keys
      assert "email_smtp_username" in keys
      assert "email_smtp_password" in keys
    end
  end

  describe "all_field_keys/0" do
    test "returns unique keys from all adapters" do
      keys = Adapters.all_field_keys()
      assert is_list(keys)
      assert "email_smtp_relay" in keys
      assert length(keys) == length(Enum.uniq(keys))
    end
  end

  describe "settings_key/2" do
    test "namespaces key with adapter" do
      assert Adapters.settings_key("brevo", "api_key") == "email_brevo_api_key"
      assert Adapters.settings_key("smtp", "relay") == "email_smtp_relay"
    end
  end
end
