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

/**
 * POST /api/auth/change-password
 * Body: { currentPassword: string, newPassword: string }
 * Requires authentication.
 */
export const POST: RequestHandler = async ({ request, locals }) => {
	if (!locals.user) {
		error(401, 'Not authenticated');
	}

	let body: { currentPassword?: string; newPassword?: string };
	try {
		body = await request.json();
	} catch {
		error(400, 'Invalid JSON body');
	}

	const currentPassword = body.currentPassword ?? '';
	const newPassword = body.newPassword ?? '';

	if (!currentPassword || !newPassword) {
		error(400, 'currentPassword and newPassword are required');
	}

	if (newPassword.length < 4) {
		error(400, 'New password must be at least 4 characters');
	}

	try {
		const ok = await changePassword(locals.user.id, currentPassword, newPassword);
		if (!ok) {
			error(401, 'Current password is incorrect');
		}
	} catch (e: unknown) {
		// Re-throw SvelteKit errors as-is
		if (e && typeof e === 'object' && 'status' in e) throw e;
		log.error('api/auth/change-password', 'unexpected error', { err: String(e) });
		error(500, 'An error occurred. Please try again.');
	}

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