defmodule ToweropsWeb.Api.V1.AgentReleaseWebhookController do
  @moduledoc """
  Webhook endpoint for CI to trigger mass agent updates.

  Called by CI after publishing a new GitHub Release. Broadcasts an update
  command to all connected agents via their existing WebSocket channels.
  """

  use ToweropsWeb, :controller

  alias Towerops.Agents

  def create(conn, _params) do
    case Agents.broadcast_mass_update() do
      {:ok, result} ->
        json(conn, %{
          status: "ok",
          notified: result.notified,
          skipped: result.skipped,
          version: result.version
        })

      {:error, reason} ->
        conn
        |> put_status(:bad_gateway)
        |> json(%{status: "error", error: inspect(reason)})
    end
  end
end
