# Seed data for some sample albums.
# Text content generated by ChatGPT 4, album covers generated by Midjourney.

require Ash.Query

album_names = Enum.map(Tunez.Seeder.albums(), & &1.name)

albums =
  Tunez.Music.Album
  |> Ash.Query.filter(name in ^album_names)
  |> Ash.read!()

album_ids = Enum.map(albums, & &1.id)
album_name_map = Enum.map(albums, &{&1.name, &1.id}) |> Map.new()

# Delete the existing records for tracks from the seed data albums
Tunez.Music.Track
|> Ash.Query.filter(album_id in ^album_ids)
|> Ash.bulk_destroy!(:destroy, %{}, authorize?: false)

# And re-insert fresh copies of them
Tunez.Seeder.albums()
|> Enum.filter(fn album -> Map.has_key?(album_name_map, album.name) end)
|> Enum.flat_map(fn album ->
  album.tracks
  |> Enum.with_index()
  |> Enum.map(fn {track, order} ->
    track
    |> Map.put(:album_id, Map.fetch!(album_name_map, album.name))
    |> Map.put(:order, order)
  end)
end)
|> Ash.bulk_create!(Tunez.Music.Track, :create, skip_unknown_inputs: [:*], return_errors?: true, authorize?: false)
