if Mix.env() == :dev do
  defmodule Berrypod.DevReset do
    @moduledoc """
    Dev-only helper to wipe all data and flush caches without restarting.

    Usage from IEx or Tidewave eval:

        Berrypod.DevReset.run()
    """

    alias Berrypod.Repo

    # Tables in deletion order (children before parents)
    @tables ~w(
      order_items
      orders
      abandoned_carts
      product_images
      product_variants
      products
      provider_connections
      favicon_variants
      images
      users_tokens
      users
      pages
      analytics_events
      newsletter_subscribers
      newsletter_campaigns
      redirects
      broken_urls
      dead_links
      activity_log
      email_suppressions
      settings
    )

    def run do
      # Reconnect the Repo in case mix ecto.reset replaced the DB file
      # while the server was running (old connections would point to a ghost file)
      Supervisor.terminate_child(Berrypod.Supervisor, Repo)
      Supervisor.restart_child(Berrypod.Supervisor, Repo)
      Process.sleep(100)

      IO.puts("Wiping all data...")

      Repo.query!("PRAGMA foreign_keys = OFF")

      for table <- @tables do
        Repo.query!("DELETE FROM \"#{table}\"")
      end

      # Clear Oban jobs too
      Repo.query!("DELETE FROM oban_jobs")

      Repo.query!("PRAGMA foreign_keys = ON")

      IO.puts("Flushing caches and runtime config...")

      # ETS caches (invalidate_all clears computed/cached values too)
      Berrypod.Settings.SettingsCache.invalidate_all()
      Berrypod.Theme.CSSCache.invalidate()
      Berrypod.Pages.PageCache.invalidate_all()

      # Redirects ETS table
      if :ets.whereis(:redirects_cache) != :undefined do
        :ets.delete_all_objects(:redirects_cache)
      end

      # Runtime Application env
      Application.put_env(:berrypod, Berrypod.Mailer, adapter: Swoosh.Adapters.Local)
      Application.put_env(:swoosh, :api_client, false)

      IO.puts("Done — visit /setup to start fresh")
      :ok
    end
  end
end
