import type { SongFilters } from "$lib/db/client-db";
import { db, ensureSeeded, getSongsWithFilters } from "$lib/db/client-db";
import type { PageLoad } from "./$types";
import { SearchParamsSchema } from "./schema";

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

	const parsed = SearchParamsSchema.safeParse(
		Object.fromEntries(url.searchParams.entries()),
	);

	const filters: SongFilters = {};
	if (parsed.success) {
		if (parsed.data.song) filters.songName = parsed.data.song;
		if (parsed.data.artist) filters.artistName = parsed.data.artist;
		if (parsed.data.anime) filters.animeName = parsed.data.anime;
		if (parsed.data.gpm !== undefined)
			filters.globalPercentMin = parsed.data.gpm;
		if (parsed.data.gpx !== undefined)
			filters.globalPercentMax = parsed.data.gpx;
		if (parsed.data.type) filters.songTypes = parsed.data.type;
	}

	// Client-only DB: on the server `db` is null, so return [] and let hydration re-run load in browser.
	if (!db) {
		return {
			filters: parsed.success ? parsed.data : {}, // Return original parsed data for form state
			songRows: [],
		};
	}

	await ensureSeeded({ fetch });

	const songRows = await getSongsWithFilters(db, filters, parsed.data?.limit);

	return {
		filters: parsed.success ? parsed.data : {}, // Return original parsed data for form state
		songRows,
	};
};
