defmodule CentralcloudCore.HostBill do
  @moduledoc """
  HostBill Admin API client.

  Uses the Admin API at /admin/api.php (version 2026-04-21).
  All requests are authenticated with api_id + api_key query params.
  """

  @spec get_client(integer()) :: {:ok, map()} | {:error, term()}
  def get_client(client_id) do
    call("getClientsDetails", %{clientid: client_id})
  end

  @spec get_clients() :: {:ok, list(map())} | {:error, term()}
  def get_clients do
    call("getClients", %{})
  end

  @spec get_client_services(integer()) :: {:ok, list(map())} | {:error, term()}
  def get_client_services(client_id) do
    call("getClientsProducts", %{clientid: client_id})
  end

  @spec get_invoices(integer()) :: {:ok, list(map())} | {:error, term()}
  def get_invoices(client_id) do
    call("getInvoices", %{clientid: client_id})
  end

  # ---------------------------------------------------------------------------
  # Private

  defp call(action, params) do
    cfg = Application.fetch_env!(:centralcloud_core, :hostbill)

    query =
      Map.merge(params, %{
        api_id:  cfg[:api_id],
        api_key: cfg[:api_key],
        call:    action
      })

    url = cfg[:base_url] <> "/admin/api.php"

    case Req.post(url, form: query) do
      {:ok, %{status: 200, body: body}} -> {:ok, body}
      {:ok, %{status: status}}          -> {:error, {:http, status}}
      {:error, reason}                  -> {:error, reason}
    end
  end
end
