import { PGlite } from "@electric-sql/pglite";
import { drizzle } from "drizzle-orm/pglite";
import { migrate } from "drizzle-orm/pglite/migrator";
import * as schema from "../../src/db/schema.ts";

type Db = ReturnType<typeof drizzle<typeof schema>>;

export async function createTestDb() {
	const client = new PGlite();
	const db = drizzle(client, { schema });

	// Apply all migrations to create tables
	await migrate(db, { migrationsFolder: "./drizzle-pg" });

	// Seed a test user
	const [user] = await db
		.insert(schema.users)
		.values({ logtoSub: "test-user-sub" })
		.returning();

	// Seed per-user Uncategorized category
	await db
		.insert(schema.categories)
		.values({ name: "Uncategorized", icon: "package", userId: user.id });

	return { db, userId: user.id };
}

export async function createSecondTestUser(db: Db) {
	const [user] = await db
		.insert(schema.users)
		.values({ logtoSub: "test-user-2-sub" })
		.returning();

	await db
		.insert(schema.categories)
		.values({ name: "Uncategorized", icon: "package", userId: user.id });

	return user.id;
}
