defmodule Towerops.Workers.ProfileImportWorker do
  @moduledoc """
  Background worker for importing device SNMP profiles.

  Enqueued when:
  - Superuser uploads profiles via API endpoint POST /api/v1/admin/profiles/import

  Queue: maintenance
  """

  alias Towerops.DeviceProfiles
  alias Towerops.DeviceProfiles.Importer

  require Logger

  @doc """
  Imports device profiles from JSON data.

  ## Parameters
  - profiles: List of profile maps with detection and discovery data
  - job_id: Unique identifier for tracking the import job

  ## Returns
  - :ok on completion (logs individual profile successes/failures)
  """
  def perform(profiles, job_id) when is_list(profiles) do
    Logger.info("Starting profile import job #{job_id} with #{length(profiles)} profiles")

    results =
      Enum.map(profiles, fn profile_data ->
        os_name = profile_data["os"]

        case import_profile(profile_data) do
          {:ok, profile} ->
            Logger.info("[#{job_id}] Successfully imported profile: #{profile.os}")
            {:ok, profile}

          {:error, reason} ->
            Logger.error("[#{job_id}] Failed to import profile #{os_name}: #{inspect(reason)}")
            {:error, os_name, reason}
        end
      end)

    {successes, failures} = Enum.split_with(results, &match?({:ok, _}, &1))

    Logger.info("[#{job_id}] Import complete: #{length(successes)} succeeded, #{length(failures)} failed")

    :ok
  end

  # Private functions

  defp import_profile(%{"os" => os_name, "detection" => detection_data} = data) do
    # Delete existing profile first (force replace)
    if profile = DeviceProfiles.get_profile(os_name) do
      DeviceProfiles.delete_profile(profile)
    end

    # Import directly from data structures
    case Importer.import_profile_from_data(
           detection_data,
           data["discovery"]
         ) do
      {:ok, profile} ->
        {:ok, profile}

      {:error, reason} ->
        {:error, reason}
    end
  end

  defp import_profile(_invalid_data) do
    {:error, "Missing required fields: os and detection"}
  end
end
