defmodule Towerops.Workers.PreseemBaselineWorker do
  @moduledoc """
  Nightly Oban cron worker that computes device baselines and fleet profiles
  for all organizations with enabled Preseem integrations.
  """
  use Oban.Worker, queue: :maintenance

  alias Towerops.Integrations
  alias Towerops.Preseem.Baseline
  alias Towerops.Preseem.FleetIntelligence
  alias Towerops.Preseem.Insights

  require Logger

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

    Enum.each(integrations, fn integration ->
      org_id = integration.organization_id
      compute_for_org(org_id)
    end)

    :ok
  end

  defp compute_for_org(org_id) do
    {:ok, baseline_count} = Baseline.compute_baselines(org_id)
    Logger.info("Preseem baselines computed for org #{org_id}: #{baseline_count} devices")

    {:ok, profile_count} = FleetIntelligence.compute_fleet_profiles(org_id)
    Logger.info("Preseem fleet profiles computed for org #{org_id}: #{profile_count} models")

    {:ok, insight_count} = Insights.generate_insights(org_id)
    Logger.info("Preseem insights generated for org #{org_id}: #{insight_count} new insights")
  rescue
    error ->
      Logger.error("Preseem baseline/fleet computation failed for org #{org_id}: #{inspect(error)}")
  end
end
