# auth = (
#   ["SCHEDULE_USER", "SCHEDULE_KEY"]
#   |> Enum.map(&System.get_env/1)
#   |> Enum.join(":")
#   |> Base.encode64
# )
# headers = [ "Authorization": "Basic #{auth}", "Accept": "application/json" ]
# address = "https://acuityscheduling.com/api/v1/appointments"
# response = case Req.get(address, headers: headers) do
#   {:error, r} -> IO.inspect r; []
#   {:ok, r = %Req.Response{status: 400}} -> IO.inspect r; []
#   {:ok, r } -> r.body
# end

defmodule Acuity do
  def auth do
    ["SCHEDULE_USER", "SCHEDULE_KEY"]
    |> Enum.map(&System.get_env/1)
    |> Enum.join(":")
    |> Base.encode64
  end

  def headers do
    [ "Authorization": "Basic #{auth()}", "Accept": "application/json" ]
  end

  def query(address, body \\ %{}) do
    params = "?" <> (body |> Enum.map(fn {a, b} -> "#{a}=#{b}" end) |> Enum.join("&"))
    case Req.get(
      "https://acuityscheduling.com/api/v1/" <> address <> params,
      headers: headers()
    ) do
      {:error, r} -> IO.inspect r; []
      {:ok, r = %Req.Response{status: 400}} -> IO.inspect r; []
      {:ok, r } -> r.body
    end
  end

  def dump do
    clock = DateTime.now("Etc/UTC") |> elem(1)
    bookings = (2020..clock.year) |> Enum.map(fn year -> Acuity.query("appointments", %{
      max: 40000,
      minDate: "#{year}-01-01",
      maxDate: "#{year}-12-31",
      excludeForms: true,
    }) end) |> List.flatten
    File.write("#{clock |> Date.to_string}.bookings.json", bookings |> Jason.encode!)
  end
end
