import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { unsaveBook } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';

/**
 * POST /api/library/bulk-remove
 * Body: { slugs: string[] }
 * Removes multiple books from the user's library at once.
 */
export const POST: RequestHandler = async ({ request, locals }) => {
	const body = await request.json().catch(() => null);
	const slugs: unknown = body?.slugs;
	if (!Array.isArray(slugs) || slugs.length === 0) {
		error(400, 'slugs must be a non-empty array');
	}
	const validSlugs = (slugs as unknown[]).filter((s): s is string => typeof s === 'string');
	if (validSlugs.length === 0) error(400, 'no valid slugs provided');

	const results = await Promise.allSettled(
		validSlugs.map((slug) => unsaveBook(locals.sessionId, slug, locals.user?.id))
	);

	const failed = results
		.map((r, i) => (r.status === 'rejected' ? validSlugs[i] : null))
		.filter(Boolean);

	if (failed.length > 0) {
		log.error('library', 'bulk-remove partial failure', { failed });
	}

	return json({ ok: true, removed: validSlugs.length - failed.length, failed });
};
