defmodule Mv.VereinfachtTest do
  @moduledoc """
  Tests for Mv.Vereinfacht business logic.

  No real API calls; tests "not configured" path and pure helpers (format_error).
  """
  use Mv.DataCase, async: false

  alias Mv.Vereinfacht

  setup do
    clear_vereinfacht_env()
    :ok
  end

  describe "sync_member/1" do
    test "returns :ok when Vereinfacht is not configured (no-op)" do
      member = Mv.Fixtures.member_fixture()

      assert Vereinfacht.sync_member(member) == :ok
    end
  end

  describe "sync_members_without_contact/0" do
    test "returns {:error, :not_configured} when Vereinfacht is not configured" do
      assert Vereinfacht.sync_members_without_contact() == {:error, :not_configured}
    end
  end

  describe "format_error/1" do
    test "formats HTTP error with detail" do
      assert Vereinfacht.format_error({:http, 422, "The email field is required."}) ==
               "Vereinfacht: The email field is required."
    end

    test "formats HTTP error without detail" do
      assert Vereinfacht.format_error({:http, 500, nil}) ==
               "Vereinfacht: API error (HTTP 500)."
    end

    test "formats request_failed" do
      assert Vereinfacht.format_error({:request_failed, %{reason: :econnrefused}}) ==
               "Vereinfacht: Request failed (e.g. connection error)."
    end

    test "formats invalid_response and other terms" do
      assert Vereinfacht.format_error({:invalid_response, %{}}) ==
               "Vereinfacht: Invalid API response."

      assert Vereinfacht.format_error(:timeout) == "Vereinfacht: :timeout"
    end
  end

  defp clear_vereinfacht_env do
    System.delete_env("VEREINFACHT_API_URL")
    System.delete_env("VEREINFACHT_API_KEY")
    System.delete_env("VEREINFACHT_CLUB_ID")
  end
end
