defmodule Berrypod.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
    # Create ETS tables here so the supervisor process owns them (live forever).
    # The GenServers/Tasks below only warm them with data from the DB.
    Berrypod.Redirects.create_table()
    Berrypod.Settings.SettingsCache.create_table()
    Berrypod.ActivityLog.ObanTelemetryHandler.attach()

    children = [
      # Rate limiting (ETS-backed, must start early)
      Berrypod.RateLimit,
      BerrypodWeb.Telemetry,
      Berrypod.Repo,
      {Ecto.Migrator,
       repos: Application.fetch_env!(:berrypod, :ecto_repos), skip: skip_migrations?()},
      # Seed default theme settings if none exist (first boot)
      Supervisor.child_spec({Task, &Berrypod.Release.seed_defaults/0}, id: :seed_defaults),
      # Load encrypted secrets from DB into Application env
      {Task, &Berrypod.Secrets.load_all/0},
      # Load email adapter config from DB (after secrets are available)
      Supervisor.child_spec({Task, &Berrypod.Mailer.load_config/0}, id: :load_email_config),
      {DNSCluster, query: Application.get_env(:berrypod, :dns_cluster_query) || :ignore},
      {Phoenix.PubSub, name: Berrypod.PubSub},
      # Warm redirect cache from DB (table already created above)
      Supervisor.child_spec({Task, &Berrypod.Redirects.warm_cache/0}, id: :redirect_cache),
      # Background job processing
      {Oban, Application.fetch_env!(:berrypod, Oban)},
      # Analytics: daily-rotating salt and ETS event buffer
      Berrypod.Analytics.Salt,
      Berrypod.Analytics.Buffer,
      # Image variant cache - ensures all variants exist on startup
      Berrypod.Images.VariantCache,
      # Start to serve requests
      BerrypodWeb.Endpoint,
      # Settings cache - all non-encrypted settings in ETS (must warm before CSSCache)
      Berrypod.Settings.SettingsCache,
      # Theme CSS cache - must start after Endpoint for static_path/1 to work
      Berrypod.Theme.CSSCache,
      # Page definition cache - loads page block lists into ETS
      Berrypod.Pages.PageCache,
      # URL routes cache - custom slugs and prefixes
      BerrypodWeb.R
    ]

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

    log_setup_secret_if_needed()

    result
  end

  defp log_setup_secret_if_needed do
    if Application.get_env(:berrypod, :env) != :test do
      unless Berrypod.Accounts.has_admin?() do
        secret = Berrypod.Setup.setup_secret()

        require Logger

        Logger.info("Setup secret: #{secret} — visit /setup to create your admin account")
      end
    end
  end

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

  defp skip_migrations?() do
    # By default, sqlite migrations are run when using a release
    System.get_env("RELEASE_NAME") == nil
  end
end
