import seedData from "./global-items-seed.json";
import { db as prodDb } from "./index.ts";
import { globalItems, tags } from "./schema.ts";

type Db = typeof prodDb;

const SEED_TAGS = [
	// Hobby / activity tags (used by onboarding hobby picker)
	"bikepacking",
	"cycling",
	"hiking",
	"backpacking",
	"camping",
	"climbing",
	"mountaineering",
	"road-cycling",
	"gravel",
	"running",
	"trail-running",
	// Bag types
	"handlebar-bag",
	"framebag",
	"saddlebag",
	"top-tube-bag",
	"stem-bag",
	"fork-bag",
	"feed-bag",
	"dry-bag",
	"stuff-sack",
	// Bike bags (parent)
	"bike-bag",
	// Shelter
	"tent",
	"bivy",
	"tarp",
	"hammock",
	// Sleep system
	"sleeping-bag",
	"sleeping-pad",
	"quilt",
	"pillow",
	// Cooking
	"stove",
	"cookware",
	"mug",
	"utensils",
	// Water
	"water-filter",
	"water-bottle",
	// Lighting
	"headlamp",
	"bike-light",
	"lantern",
	// Navigation & electronics
	"gps",
	"bike-computer",
	"power-bank",
	"solar-panel",
	// Tools & repair
	"multi-tool",
	"pump",
	"repair-kit",
	"lock",
	// Clothing
	"rain-jacket",
	"base-layer",
	"gloves",
	"shoe",
];

/**
 * Seed curated tags for outdoor/adventure gear.
 * Idempotent: inserts only tags that don't already exist.
 */
export async function seedTags(db: Db = prodDb) {
	const existing = await db.select().from(tags);
	const existingNames = new Set(existing.map((t) => t.name));

	for (const name of SEED_TAGS) {
		if (!existingNames.has(name)) {
			await db.insert(tags).values({ name });
		}
	}
}

/**
 * Seed the global items table with initial bikepacking gear data.
 * Idempotent: skips if any rows already exist.
 */
export async function seedGlobalItems(db: Db = prodDb) {
	const existing = await db.select().from(globalItems).limit(1);
	if (existing.length > 0) return;

	for (const item of seedData) {
		await db.insert(globalItems).values({
			brand: item.brand,
			model: item.model,
			category: item.category ?? null,
			weightGrams: item.weightGrams ?? null,
			priceCents: item.priceCents ?? null,
			description: item.description ?? null,
		});
	}

	await seedTags(db);
}
