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

/**
 * POST /api/progress/[slug]
 * Body: { chapter: number }
 * Records the user's reading position for a specific book.
 *
 * This is a slug-in-path variant of POST /api/progress (which takes slug in body).
 * Used by the iOS app where slug is part of the URL path.
 */
export const POST: RequestHandler = async ({ params, request, locals }) => {
	const { slug } = params;
	const body = await request.json().catch(() => null);

	if (!body || typeof body.chapter !== 'number') {
		error(400, 'Invalid body — expected { chapter: number }');
	}

	try {
		await setProgress(locals.sessionId, slug, body.chapter, locals.user?.id);
	} catch (e) {
		log.error('api/progress/[slug]', 'setProgress failed', {
			slug,
			chapter: body.chapter,
			err: String(e)
		});
		error(500, 'Failed to save progress');
	}

	return json({ ok: true });
};

/**
 * DELETE /api/progress/[slug]
 * Removes reading progress for a specific book (removes from library/continue reading).
 */
export const DELETE: RequestHandler = async ({ params, locals }) => {
	const { slug } = params;

	try {
		await deleteProgress(locals.sessionId, slug, locals.user?.id);
	} catch (e) {
		log.error('api/progress/[slug]', 'deleteProgress failed', {
			slug,
			err: String(e)
		});
		error(500, 'Failed to delete progress');
	}

	return json({ ok: true });
};
