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

/**
 * POST /api/comment/[id]/vote
 * Body: { vote: 'up' | 'down' }
 * Casts, changes, or toggles off a vote on a comment.
 * Works for both authenticated and anonymous users (session-scoped).
 * Returns the updated comment.
 */
export const POST: RequestHandler = async ({ params, request, locals }) => {
	const { id } = params;
	let body: { vote?: string };
	try {
		body = await request.json();
	} catch {
		error(400, 'Invalid JSON body');
	}

	if (body.vote !== 'up' && body.vote !== 'down') {
		error(400, 'vote must be "up" or "down"');
	}

	try {
		const updated = await voteComment(id, body.vote, locals.sessionId, locals.user?.id);
		return json(updated);
	} catch (e) {
		log.error('api/comment/[id]/vote', 'voteComment failed', { id, err: String(e) });
		error(500, 'Failed to record vote');
	}
};
