defmodule Towerops.Workers.GaiiaInsightWorker do
  @moduledoc """
  Oban cron worker that generates Gaiia-based insights.

  Runs nightly to detect:
  - `reconciliation_finding`: Untracked devices, ghost devices, data mismatches
  """
  use Oban.Worker, queue: :maintenance

  alias Towerops.Gaiia.Reconciliation
  alias Towerops.Integrations
  alias Towerops.Preseem.Insights

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    integrations = Integrations.list_enabled_integrations("gaiia")

    Enum.each(integrations, fn integration ->
      process_reconciliation(integration.organization_id)
    end)

    :ok
  end

  defp process_reconciliation(organization_id) do
    result = Reconciliation.reconcile(organization_id)

    generate_untracked_insights(organization_id, result.untracked_devices)
    generate_ghost_insights(organization_id, result.ghost_devices)
    generate_mismatch_insights(organization_id, result.data_mismatches)
  end

  defp generate_untracked_insights(organization_id, untracked_devices) do
    count = length(untracked_devices)

    if count > 0 do
      Insights.insert_insight_if_new(%{
        organization_id: organization_id,
        type: "reconciliation_finding",
        urgency: "info",
        channel: "passive",
        source: "gaiia",
        dedup_key: "untracked",
        title: "#{count} device(s) not tracked in Gaiia",
        description:
          "#{count} device(s) discovered by Towerops have no matching Gaiia inventory item. " <>
            "Consider adding them to Gaiia for complete subscriber impact tracking.",
        metadata: %{
          "dedup_key" => "untracked",
          "finding_type" => "untracked",
          "count" => count,
          "device_names" => untracked_devices |> Enum.take(10) |> Enum.map(& &1.device.name)
        }
      })
    end
  end

  defp generate_ghost_insights(organization_id, ghost_devices) do
    count = length(ghost_devices)

    if count > 0 do
      Insights.insert_insight_if_new(%{
        organization_id: organization_id,
        type: "reconciliation_finding",
        urgency: "warning",
        channel: "proactive",
        source: "gaiia",
        dedup_key: "ghost",
        title: "#{count} Gaiia item(s) reference missing devices",
        description:
          "#{count} Gaiia inventory item(s) are mapped to devices that no longer exist in Towerops. " <>
            "Review and clean up stale mappings.",
        metadata: %{
          "dedup_key" => "ghost",
          "finding_type" => "ghost",
          "count" => count
        }
      })
    end
  end

  defp generate_mismatch_insights(organization_id, data_mismatches) do
    count = length(data_mismatches)

    if count > 0 do
      Insights.insert_insight_if_new(%{
        organization_id: organization_id,
        type: "reconciliation_finding",
        urgency: "info",
        channel: "passive",
        source: "gaiia",
        dedup_key: "mismatch",
        title: "#{count} data mismatch(es) between Towerops and Gaiia",
        description:
          "#{count} device(s) have mismatched data between Towerops and Gaiia inventory. " <>
            "Review IP addresses and other fields for accuracy.",
        metadata: %{
          "dedup_key" => "mismatch",
          "finding_type" => "mismatch",
          "count" => count
        }
      })
    end
  end
end
