import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getUserByUsername } from '$lib/server/pocketbase';
import { resolveAvatarUrl } from '$lib/server/minio';

/**
 * GET /api/auth/me
 * Returns the currently authenticated user from the request's auth cookie.
 * Returns 401 if not authenticated.
 */
export const GET: RequestHandler = async ({ locals }) => {
	if (!locals.user) {
		error(401, 'Not authenticated');
	}
	// Fetch full record from PocketBase to get avatar_url
	const record = await getUserByUsername(locals.user.username).catch(() => null);
	const avatarUrl = await resolveAvatarUrl(locals.user.id, record?.avatar_url).catch(() => null);
	return json({
		id: locals.user.id,
		username: locals.user.username,
		role: locals.user.role,
		avatar_url: avatarUrl
	});
};
