defmodule Aprsme.Workers.PacketCleanupWorker do
  @moduledoc """
  Worker for cleaning up old APRS packet data.

  Cleans up old `bad_packets` records via standard DELETE. Packet partition
  retention is owned exclusively by `Aprsme.PartitionManager`.
  """

  import Ecto.Query

  alias Aprsme.BadPacket
  alias Aprsme.Repo

  require Logger

  @spec perform(map()) :: :ok | {:error, String.t()}
  def perform(_args) do
    Logger.info("Starting scheduled bad-packet cleanup")
    bad_packet_count = cleanup_old_bad_packets()

    Logger.info("Bad-packet cleanup complete: removed #{bad_packet_count} expired records")

    :ok
  rescue
    error ->
      Logger.error("Packet cleanup failed: #{inspect(error)}\n#{inspect(__STACKTRACE__)}")
      {:error, "Cleanup failed: #{inspect(error)}"}
  end

  defp cleanup_old_bad_packets do
    retention_days = Application.get_env(:aprsme, :packet_retention_days, 7)
    cutoff_time = DateTime.add(DateTime.utc_now(), -retention_days * 86_400, :second)

    {deleted_count, _} =
      Repo.delete_all(from(b in BadPacket, where: b.attempted_at < ^cutoff_time))

    deleted_count
  rescue
    error ->
      Logger.error("Failed to clean up bad packets: #{inspect(error)}")
      0
  end
end
