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

const VALID_SHELVES: ShelfName[] = ['', 'plan_to_read', 'completed', 'dropped'];

/**
 * POST /api/library/bulk-shelf
 * Body: { slugs: string[], shelf: ShelfName }
 * Moves multiple books to the given shelf at once.
 */
export const POST: RequestHandler = async ({ request, locals }) => {
	const body = await request.json().catch(() => null);
	const slugs: unknown = body?.slugs;
	const shelf: unknown = body?.shelf;

	if (!Array.isArray(slugs) || slugs.length === 0) {
		error(400, 'slugs must be a non-empty array');
	}
	if (typeof shelf !== 'string' || !VALID_SHELVES.includes(shelf as ShelfName)) {
		error(400, 'invalid shelf value');
	}

	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) =>
			updateBookShelf(locals.sessionId, slug, shelf as ShelfName, 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-shelf partial failure', { failed, shelf });
	}

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