# Script for populating the database. You can run it as:
#
#     mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
#     Firehose.Repo.insert!(%Firehose.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.

if Mix.env() == :dev do
  import Ecto.Query
  alias Firehose.Accounts

  # Get or create demo user
  user = Accounts.get_user_by_email("demo@example.com")

  unless user do
    {:ok, user} = Accounts.register_user(%{email: "demo@example.com"})
  end

  # Ensure user is confirmed to allow password login and avoid magic link conflicts
  if is_nil(user.confirmed_at) do
    Firehose.Repo.update_all(
      from(u in Accounts.User, where: u.email == ^"demo@example.com"),
      set: [confirmed_at: DateTime.utc_now()]
    )

    # Reload user after confirmation
    user = Accounts.get_user_by_email("demo@example.com")
  end

  # Set password if not already set
  unless user.hashed_password do
    {:ok, {_user, _tokens}} = Accounts.update_user_password(user, %{password: "password123!"})
  end
end
