defmodule SimpleshopTheme.Secrets do
  @moduledoc """
  Loads encrypted secrets from the database into Application env at runtime.

  Secrets are stored encrypted in the settings table via `Settings.put_secret/2`
  and loaded into the appropriate Application config on startup. This keeps all
  credentials in the portable SQLite database, encrypted via the Vault module.

  The only external dependency is `SECRET_KEY_BASE` (used to derive encryption keys).
  """

  alias SimpleshopTheme.Settings

  require Logger

  @doc """
  Loads all secrets from the database into Application env.

  Called at startup from the supervision tree, after the Repo is ready.
  """
  def load_all do
    load_stripe_config()
  end

  @doc """
  Loads Stripe credentials from encrypted settings into Application env.
  """
  def load_stripe_config do
    api_key = Settings.get_secret("stripe_api_key")
    signing_secret = Settings.get_secret("stripe_signing_secret")

    if api_key do
      Application.put_env(:stripity_stripe, :api_key, api_key)
      Logger.debug("Stripe API key loaded from database")
    end

    if signing_secret do
      Application.put_env(:stripity_stripe, :signing_secret, signing_secret)
      Logger.debug("Stripe webhook secret loaded from database")
    end

    :ok
  end
end
