# Script for populating the database. You can run it as:
#
#     mix run priv/repo/seeds.exs
#
# Bootstrap runs in all environments. Dev seeds (members, groups, sample data)
# run only in dev and test. Skips entirely if bootstrap was already applied
# (admin user exists), so safe to run on every start. Set FORCE_SEEDS=true to
# re-run seeds even when already applied.
#
# In production (release): seeds are run via Mv.Release.run_seeds/0 from the
# container entrypoint. Set RUN_DEV_SEEDS=true to also run dev seeds there.
#
# Compiler option ignore_module_conflict is set only during seed evaluation
# so that eval_file of bootstrap/dev does not emit "redefining module" warnings;
# it is always restored in `after` to avoid hiding real conflicts elsewhere.

_ = Application.ensure_all_started(:mv)

if Mv.Release.bootstrap_seeds_applied?() and System.get_env("FORCE_SEEDS") != "true" do
  IO.puts("Seeds already applied. Skipping. (Set FORCE_SEEDS=true to override)")
else
  prev = Code.compiler_options()
  Code.compiler_options(ignore_module_conflict: true)

  try do
    # Always run bootstrap (fee types, custom fields, roles, admin, system user, settings)
    Code.eval_file("priv/repo/seeds_bootstrap.exs")

    # In dev and test only: run dev seeds (20 members, groups, custom field values)
    if Mix.env() in [:dev, :test] do
      Code.eval_file("priv/repo/seeds_dev.exs")
    end

    IO.puts("✅ All seeds completed.")
  after
    Code.compiler_options(prev)
  end
end
