import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { upsertDiscoveryVote, clearDiscoveryVotes, undoDiscoveryVote, saveBook } from '$lib/server/pocketbase';

const VALID_ACTIONS = ['like', 'skip', 'nope', 'read_now'] as const;
type Action = (typeof VALID_ACTIONS)[number];

export const POST: RequestHandler = async ({ request, locals }) => {
	const body = await request.json().catch(() => null);
	if (!body || typeof body.slug !== 'string' || !VALID_ACTIONS.includes(body.action)) {
		error(400, 'Expected { slug, action }');
	}
	const action = body.action as Action;
	try {
		await upsertDiscoveryVote(locals.sessionId, body.slug, action, locals.user?.id);
		if (action === 'like' || action === 'read_now') {
			await saveBook(locals.sessionId, body.slug, locals.user?.id);
		}
	} catch (e) {
		error(500, 'Failed to record vote');
	}
	return json({ ok: true });
};

// DELETE /api/discover/vote          → clear all (deck reset)
// DELETE /api/discover/vote?slug=... → undo single vote
export const DELETE: RequestHandler = async ({ url, locals }) => {
	const slug = url.searchParams.get('slug');
	try {
		if (slug) {
			await undoDiscoveryVote(locals.sessionId, slug, locals.user?.id);
		} else {
			await clearDiscoveryVotes(locals.sessionId, locals.user?.id);
		}
	} catch {
		error(500, 'Failed to clear votes');
	}
	return json({ ok: true });
};
