# https://hex.pm/packages/airship
defmodule AirTable.Base do
  use GenServer

  def launch(base, key) do
    {:ok, pid} = GenServer.start_link(__MODULE__, {base, key})
    pid
  end

  def start_link(call) do
    GenServer.start_link(__MODULE__, call, name: __MODULE__)
  end

  @impl true
  def init({base, key}) do
    {:ok,
      Req.new(base_url: "https://api.airtable.com/v0/#{base}/")
      |> Req.Request.put_header("Authorization", "Bearer #{key}")
    }
  end

  @impl true
  def handle_call({:get, resource, call}, _from, db) do
    {:reply,
      Req.get!(db, [{ :url, resource } | call ]),
      db}
  end

  def all(resource, params \\ %{}),
    do: GenServer.call(__MODULE__, {:get, resource, params: params}).body["records"]
end
