defmodule Aprsme.DeploymentNotifier do
  @moduledoc """
  Notifies connected clients about deployment changes.
  Called from the release module when a deployment is detected.
  """

  use GenServer

  require Logger

  def start_link(opts \\ []) do
    GenServer.start_link(__MODULE__, opts, name: __MODULE__)
  end

  @impl true
  def init(_opts) do
    if System.get_env("DEPLOYED_AT"),
      do: :ok = Process.send_after(self(), :notify_deployment, 10_000),
      else: :ok

    {:ok, %{}}
  end

  @impl true
  def handle_info(:notify_deployment, state) do
    deployed_at = Aprsme.Release.deployed_at()
    :ok = notify_deployment(deployed_at)
    Logger.info("Deployment notification sent for timestamp: #{deployed_at}")
    {:noreply, state}
  end

  @doc """
  Notify about a new deployment immediately.
  """
  def notify_deployment(deployed_at) do
    Phoenix.PubSub.broadcast(
      Aprsme.PubSub,
      "deployment_events",
      {:new_deployment, %{deployed_at: deployed_at}}
    )
  end
end
