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

/**
 * GET /api/progress/audio-time?slug=&chapter=
 * Returns the last saved audio position for a chapter, or null.
 */
export const GET: RequestHandler = async ({ url, locals }) => {
	const slug = url.searchParams.get('slug');
	const chapterParam = url.searchParams.get('chapter');

	if (!slug || !chapterParam) {
		error(400, 'Missing slug or chapter query params');
	}

	const chapter = parseInt(chapterParam, 10);
	if (isNaN(chapter)) {
		error(400, 'chapter must be a number');
	}

	try {
		const audioTime = await getAudioTime(locals.sessionId, slug, chapter, locals.user?.id);
		return json({ audioTime });
	} catch (e) {
		log.error('audio-time', 'GET failed', { slug, chapter, err: String(e) });
		error(500, 'Failed to load audio time');
	}
};

/**
 * PATCH /api/progress/audio-time
 * Body: { slug: string, chapter: number, audioTime: number }
 * Saves the current audio playback position.
 */
export const PATCH: RequestHandler = async ({ request, locals }) => {
	const body = await request.json().catch(() => null);

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

	try {
		await setAudioTime(locals.sessionId, body.slug, body.chapter, body.audioTime, locals.user?.id);
	} catch (e) {
		log.error('audio-time', 'PATCH failed', { slug: body.slug, chapter: body.chapter, err: String(e) });
		error(500, 'Failed to save audio time');
	}
	return json({ ok: true });
};
