defmodule Towerops.Workers.BackupTimeoutWorker do
  @moduledoc """
  Oban worker that marks stale backup requests as timed out.

  Runs every 10 minutes via cron schedule. Marks any backup requests that have
  been pending for more than 5 minutes as "timeout" to prevent tracking table
  from accumulating stale entries.
  """

  use Oban.Worker, queue: :maintenance, max_attempts: 1

  alias Towerops.Devices.BackupRequests

  require Logger

  @timeout_minutes 5

  @impl Oban.Worker
  @spec perform(Oban.Job.t()) :: :ok
  def perform(%Oban.Job{}) do
    cutoff = DateTime.add(DateTime.utc_now(), -@timeout_minutes * 60, :second)
    timeout_count = BackupRequests.mark_timed_out_requests(cutoff)

    if timeout_count > 0 do
      Logger.warning("Marked #{timeout_count} backup requests as timeout")
    end

    :ok
  end
end
