defmodule Berrypod.Release do
  @moduledoc """
  Release tasks that can be run via `bin/migrate` or `bin/berrypod eval`.

  Migrations run automatically on startup (see Application), so this is mainly
  useful as a standalone tool for debugging or manual recovery.
  """

  @app :berrypod

  def migrate do
    load_app()

    for repo <- repos() do
      {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
    end
  end

  @doc """
  Seeds default theme settings if none exist.

  Called on every boot but only writes to the DB on first run
  (when the settings table is empty). Safe to call repeatedly.
  """
  def seed_defaults do
    alias Berrypod.Settings

    case Settings.get_setting("theme_settings") do
      nil ->
        {:ok, _} = Settings.apply_preset(:studio, skip_customised_flag: true)
        :ok

      _exists ->
        :ok
    end
  end

  def rollback(repo, version) do
    load_app()
    {:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
  end

  defp repos do
    Application.fetch_env!(@app, :ecto_repos)
  end

  defp load_app do
    Application.ensure_all_started(:ssl)
    Application.load(@app)
  end
end
