// Command seedrandomheroes inserts N level-1 heroes with random spawn/starter gear (not a migration).
// Usage: from backend/: go run ./cmd/seedrandomheroes -n 500
// Requires DB env vars (same as server): DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME.
package main

import (
	"context"
	"flag"
	"fmt"
	"log/slog"
	"math/rand"
	"os"
	"time"

	"github.com/denisovdennis/autohero/internal/config"
	"github.com/denisovdennis/autohero/internal/storage"
)

func main() {
	n := flag.Int("n", 500, "number of heroes to create")
	telegramBase := flag.Int64("telegram-base", 8_100_000_000_000, "first synthetic telegram_id (each hero gets base+0..n-1)")
	flag.Parse()

	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
	cfg := config.Load()
	ctx := context.Background()

	pool, err := storage.NewPostgres(ctx, cfg.DB, logger)
	if err != nil {
		logger.Error("postgres", "error", err)
		os.Exit(1)
	}
	defer pool.Close()

	store := storage.NewHeroStore(pool, logger)
	rng := rand.New(rand.NewSource(time.Now().UnixNano()))

	prefixes := []string{
		"Aldo", "Bree", "Cade", "Dara", "Ewan", "Fira", "Gorn", "Hett", "Ivor", "Jesa",
		"Kael", "Lina", "Miro", "Nyx", "Orin", "Pike", "Quin", "Riva", "Sven", "Tess",
		"Ulric", "Venn", "Wren", "Yara", "Zara",
	}

	var ok, fail int
	for i := 0; i < *n; i++ {
		tg := *telegramBase + int64(i)
		// Unique per batch: idx_heroes_name_lower — include telegramBase so re-runs with new -telegram-base never collide.
		name := fmt.Sprintf("%s_%d_%05d", prefixes[rng.Intn(len(prefixes))], *telegramBase, i)
		_, err := store.CreateHeroWithSpawn(ctx, tg, name)
		if err != nil {
			logger.Warn("create failed", "i", i, "telegram_id", tg, "name", name, "error", err)
			fail++
			continue
		}
		ok++
		if ok%100 == 0 {
			logger.Info("progress", "created", ok)
		}
	}

	logger.Info("done", "created", ok, "failed", fail, "requested", *n)
	if fail > 0 {
		os.Exit(1)
	}
}
