defmodule Towerops.Devices.EventLogger do
  @moduledoc """
  GenServer that subscribes to device events via PubSub and logs them to the database.

  This decouples event detection from event storage, allowing:
  - Faster polling without database write blocking
  - Multiple event consumers (logging, alerts, webhooks)
  - Better failure isolation
  """
  use GenServer

  alias Towerops.Devices

  require Logger

  # Client API

  def start_link(_opts) do
    GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
  end

  # Server Callbacks

  @impl true
  def init(state) do
    # device events topic
    _ = Phoenix.PubSub.subscribe(Towerops.PubSub, "device:events")
    Logger.info("EventLogger started and subscribed to device events")
    {:ok, state}
  end

  @impl true
  def handle_info({:device_event, event_attrs}, state) do
    case Devices.create_event(event_attrs) do
      {:ok, event} ->
        Logger.debug("Logged event: #{event.message}")

      {:error, changeset} ->
        Logger.error("Failed to log event: #{inspect(changeset.errors)}")
        Logger.error("Event data: #{inspect(event_attrs)}")
    end

    {:noreply, state}
  end

  @impl true
  def handle_info(_msg, state) do
    # Ignore other messages
    {:noreply, state}
  end
end
