defmodule Berrypod.Webhooks.ProductDeleteWorker do
  @moduledoc """
  Oban worker for deleting products removed from POD providers.
  """

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

  alias Berrypod.Products

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"provider_product_id" => provider_product_id}}) do
    case Products.get_provider_connection_by_type("printify") do
      nil ->
        Logger.warning("No Printify connection found for product deletion")
        {:cancel, :no_connection}

      conn ->
        case Products.get_product_by_provider(conn.id, provider_product_id) do
          nil ->
            Logger.info("Product #{provider_product_id} already deleted or not found")
            :ok

          product ->
            Logger.info("Deleting product #{product.id} (provider: #{provider_product_id})")

            case Products.delete_product(product) do
              {:ok, _} -> :ok
              {:error, reason} -> {:error, reason}
            end
        end
    end
  end

  def enqueue(provider_product_id) do
    %{provider_product_id: to_string(provider_product_id)}
    |> new()
    |> Oban.insert()
  end
end
