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

/**
 * GET /api/users/[username]
 * Returns public profile info + whether the current user is subscribed.
 */
export const GET: RequestHandler = async ({ params, locals }) => {
	const { username } = params;

	try {
		const profile = await getPublicProfile(username);
		if (!profile) error(404, `User "${username}" not found`);

		// Resolve avatar — MinIO first, fall back to OAuth provider picture
		let avatarUrl: string | null = null;
		avatarUrl = await resolveAvatarUrl(profile.id, profile.avatar_url).catch(() => null);

		// Is the current logged-in user subscribed?
		let isSubscribed = false;
		if (locals.user && locals.user.id !== profile.id) {
			const sub = await getSubscription(locals.user.id, profile.id).catch(() => null);
			isSubscribed = !!sub;
		}

		return json({
			id: profile.id,
			username: profile.username,
			avatarUrl,
			created: profile.created,
			followerCount: profile.followerCount,
			followingCount: profile.followingCount,
			isSubscribed,
			isSelf: locals.user?.id === profile.id
		});
	} catch (e) {
		if ((e as { status?: number }).status === 404) throw e;
		log.error('api/users', 'failed to load profile', { username, err: String(e) });
		error(500, 'Failed to load profile');
	}
};
