defmodule Towerops.Workers.BackupSummaryWorker do
  @moduledoc """
  Oban worker that sends daily backup summary emails.

  Runs daily at 8 AM via cron schedule. Sends email report to admins if there
  were any failed or timed-out backup requests in the past 24 hours.
  """

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

  alias Towerops.Devices.BackupRequests

  require Logger

  @impl Oban.Worker
  @spec perform(Oban.Job.t()) :: :ok
  def perform(%Oban.Job{}) do
    yesterday = DateTime.add(DateTime.utc_now(), -24 * 60 * 60, :second)

    summary = BackupRequests.summary_since(yesterday)

    Logger.info("Backup summary for past 24 hours", summary: summary)

    if summary.failed > 0 or summary.timeout > 0 do
      failed_devices = BackupRequests.list_failed_devices_since(yesterday)

      Logger.warning("Backup failures detected",
        failed_count: summary.failed,
        timeout_count: summary.timeout,
        devices: Enum.map(failed_devices, & &1.device_id)
      )
    end

    :ok
  end
end
