defmodule DaProductApp.SaasKit.Client do @moduledoc """ SaaS Kit API client for handling subscriptions, billing, and user management. """ # Do not alias HTTPoison.Response to avoid compile-time struct lookup issues # @base_url and @timeout removed: saas_kit dependency no longer present defp api_key do # Application.get_env(:saas_kit, :api_key) removed: saas_kit dependency no longer present end defp headers do [ {"Authorization", "Bearer #{api_key()}"}, {"Content-Type", "application/json"}, {"Accept", "application/json"} ] end @doc """ Make a GET request to the SaaS Kit API """ def get(path, params \\ %{}) do url = build_url(path, params) case HTTPoison.get(url, headers()) do {:ok, resp} when is_map(resp) -> status = Map.get(resp, :status_code) || Map.get(resp, "status_code") body = Map.get(resp, :body) || Map.get(resp, "body") case status do 200 -> {:ok, Jason.decode!(body)} _ -> {:error, %{status_code: status, body: body}} end {:error, error} -> {:error, error} end end @doc """ Make a POST request to the SaaS Kit API """ def post(path, body \\ %{}) do url = build_url(path) json_body = Jason.encode!(body) case HTTPoison.post(url, json_body, headers()) do {:ok, resp} when is_map(resp) -> status = Map.get(resp, :status_code) || Map.get(resp, "status_code") body = Map.get(resp, :body) || Map.get(resp, "body") if status in 200..299 do {:ok, Jason.decode!(body)} else {:error, %{status_code: status, body: body}} end {:error, error} -> {:error, error} end end @doc """ Make a PUT request to the SaaS Kit API """ def put(path, body \\ %{}) do url = build_url(path) json_body = Jason.encode!(body) case HTTPoison.put(url, json_body, headers()) do {:ok, resp} when is_map(resp) -> status = Map.get(resp, :status_code) || Map.get(resp, "status_code") body = Map.get(resp, :body) || Map.get(resp, "body") if status in 200..299 do {:ok, Jason.decode!(body)} else {:error, %{status_code: status, body: body}} end {:error, error} -> {:error, error} end end @doc """ Make a DELETE request to the SaaS Kit API """ def delete(path) do url = build_url(path) case HTTPoison.delete(url, headers()) do {:ok, resp} when is_map(resp) -> status = Map.get(resp, :status_code) || Map.get(resp, "status_code") body = Map.get(resp, :body) || Map.get(resp, "body") if status in 200..299 do {:ok, :deleted} else {:error, %{status_code: status, body: body}} end {:error, error} -> {:error, error} end end defp build_url(path, params \\ %{}) do url = "#{@base_url}#{path}" if Enum.empty?(params) do url else query_string = URI.encode_query(params) "#{url}?#{query_string}" end end end