defmodule Refuge.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application

  @impl true
  def start(_type, _args) do
    base_children = [
      RefugeWeb.Telemetry,
      Refuge.Repo,
      {DNSCluster, query: Application.get_env(:refuge, :dns_cluster_query) || :ignore},
      {Phoenix.PubSub, name: Refuge.PubSub},
      # Start the gRPC EventStore for storing and broadcasting events
      Refuge.GRPC.EventStore
    ]

    # Only start the disk-based cache store outside the test environment to avoid name conflicts in tests
    cache_children = if Mix.env() != :test, do: [Refuge.RemoteCache.DiskStore], else: []

    other_children = [
      # Start the NativeLink gRPC server using configured port (1985 default, 1989 for test)
      {GRPC.Server.Supervisor, endpoint: Refuge.NativeLink.Endpoint, port: Application.get_env(:refuge, :grpc, [])[:port] || 1985, start_server: true},
      # Start to serve requests, typically the last entry
      RefugeWeb.Endpoint
    ]

    children = base_children ++ cache_children ++ other_children

    # See https://hexdocs.pm/elixir/Supervisor.html
    # for other strategies and supported options
    opts = [strategy: :one_for_one, name: Refuge.Supervisor]
    Supervisor.start_link(children, opts)
  end

  # Tell Phoenix to update the endpoint configuration
  # whenever the application is updated.
  @impl true
  def config_change(changed, _new, removed) do
    RefugeWeb.Endpoint.config_change(changed, removed)
    :ok
  end
end
