defmodule Berrypod.Sync.ScheduledSyncWorker do
  @moduledoc """
  Oban cron worker for periodic product + shipping rate sync.

  Runs every 6 hours, enqueues a ProductSyncWorker for each enabled
  provider connection. The :sync queue (concurrency 1) serialises
  these with any manual syncs triggered from the admin UI.
  """

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

  alias Berrypod.Products

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    connections =
      Products.list_provider_connections()
      |> Enum.filter(& &1.enabled)

    if Enum.empty?(connections) do
      Logger.info("Scheduled sync: no enabled provider connections, skipping")
    else
      Logger.info("Scheduled sync: enqueuing sync for #{length(connections)} connection(s)")

      Enum.each(connections, fn conn ->
        Products.enqueue_sync(conn)
      end)
    end

    :ok
  end
end
