defmodule Towerops.Workers.CloudflareBanWorker do
  @moduledoc """
  Oban worker that pushes permanent IP bans to Cloudflare WAF.

  Triggered when an IP reaches its 3rd offense (permanent ban).
  Runs in the :maintenance queue with up to 3 retry attempts.
  """

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

  alias Towerops.Security.CloudflareClient

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"ip_address" => ip_address}}) do
    case CloudflareClient.block_ip(ip_address) do
      {:ok, _response} ->
        Logger.info("Successfully pushed permanent ban to Cloudflare: #{ip_address}")
        :ok

      {:error, :not_configured} ->
        Logger.debug("Cloudflare not configured, skipping edge block for #{ip_address}")
        # Don't retry if credentials aren't configured
        :ok

      {:error, reason} ->
        Logger.error("Failed to push ban to Cloudflare for #{ip_address}: #{inspect(reason)}")
        # Return error to trigger Oban retry
        {:error, reason}
    end
  end

  @doc """
  Enqueues a job to push an IP ban to Cloudflare.
  """
  def enqueue(ip_address) do
    %{ip_address: ip_address}
    |> new()
    |> Oban.insert()
  end
end
