defmodule MicrowavepropWeb.ContactMapController do
  @moduledoc """
  Serves the contact map JSON payload as a standalone HTTP endpoint. Keeps
  the ~5 MB blob out of the `/contacts/map` LiveView's initial HTML response
  and lets the browser's native `Content-Encoding: gzip` handling do the
  compression. The payload itself is served from `Microwaveprop.Cache` via
  `Radio.contact_map_payload/0`.
  """
  use MicrowavepropWeb, :controller

  alias Microwaveprop.Cache
  alias Microwaveprop.Radio

  @cache_key {__MODULE__, :gzipped_payload}
  @cache_ttl_ms 10 * 60 * 1_000

  @spec show(Plug.Conn.t(), map()) :: Plug.Conn.t()
  def show(conn, _params) do
    {body, encoding} = gzipped_or_plain_body(conn)

    conn
    |> put_resp_content_type("application/json")
    |> maybe_put_encoding(encoding)
    |> put_resp_header("cache-control", "public, max-age=60")
    |> send_resp(200, body)
  end

  defp gzipped_or_plain_body(conn) do
    if accepts_gzip?(conn) do
      {gzipped_payload(), :gzip}
    else
      %{json: iodata} = Radio.contact_map_payload()
      {IO.iodata_to_binary(iodata), :identity}
    end
  end

  defp gzipped_payload do
    Cache.fetch_or_store(@cache_key, @cache_ttl_ms, fn ->
      %{json: iodata} = Radio.contact_map_payload()
      :zlib.gzip(IO.iodata_to_binary(iodata))
    end)
  end

  defp accepts_gzip?(conn) do
    case get_req_header(conn, "accept-encoding") do
      [value | _] -> String.contains?(value, "gzip")
      _ -> false
    end
  end

  defp maybe_put_encoding(conn, :gzip), do: put_resp_header(conn, "content-encoding", "gzip")
  defp maybe_put_encoding(conn, :identity), do: conn
end
