defmodule SimpleshopTheme.Orders.FulfilmentStatusWorker do
  @moduledoc """
  Oban Cron worker that polls the fulfilment provider for status updates.

  Runs every 30 minutes as a fallback for missed webhook events.
  Only checks orders that are submitted or processing (i.e. awaiting
  further status transitions).
  """

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

  alias SimpleshopTheme.Orders

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    orders = Orders.list_submitted_orders()

    if orders == [] do
      :ok
    else
      Logger.info("Polling fulfilment status for #{length(orders)} order(s)")

      Enum.each(orders, fn order ->
        refresh_order(order)
        Process.sleep(200)
      end)

      :ok
    end
  end

  defp refresh_order(order) do
    case Orders.refresh_fulfilment_status(order) do
      {:ok, updated} ->
        if updated.fulfilment_status != order.fulfilment_status do
          Logger.info(
            "Order #{order.order_number} status: #{order.fulfilment_status} → #{updated.fulfilment_status}"
          )
        end

      {:error, reason} ->
        Logger.warning(
          "Failed to refresh status for order #{order.order_number}: #{inspect(reason)}"
        )
    end
  end
end
