import { z } from "zod";
// Import client-db index directly.
// On the server, `db` will be null (because `browser` is false in that module).
import { db, ensureSeeded } from "$lib/db/client-db";
import { getAnimeWithSongsByAnnId } from "$lib/db/client-db/queries";
import type { PageLoad } from "./$types";

const ParamsSchema = z
	.object({
		annId: z.coerce.number().int().positive(),
	})
	.strict();

export const load: PageLoad = async ({ params, fetch, depends }) => {
	depends("clientdb:anime");
	depends("clientdb:songs");

	const parsed = ParamsSchema.safeParse(params);

	// Always return a stable hydration-friendly shape.
	// (`+page.svelte` can decide how to show not-found/error states.)
	if (!parsed.success) {
		return {
			annId: null as number | null,
			animeWithSongs: null as Awaited<
				ReturnType<typeof getAnimeWithSongsByAnnId>
			> | null,
		};
	}

	const annId = parsed.data.annId;

	// Client-only DB: on the server `db` is null.
	// Return null here and let the page re-run `load()` in the browser after hydration
	// (see `invalidate(...)` pattern used in `/list`).
	if (!db) {
		return {
			annId,
			animeWithSongs: null as Awaited<
				ReturnType<typeof getAnimeWithSongsByAnnId>
			> | null,
		};
	}

	await ensureSeeded({ fetch });

	const animeWithSongs = await getAnimeWithSongsByAnnId(db, annId);

	return {
		annId,
		animeWithSongs,
	};
};
