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

export const load: PageServerLoad = async ({ params, locals }) => {
	const { username } = params;

	const profile = await getPublicProfile(username).catch(() => null);
	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);

	// Subscription state for the logged-in visitor
	let isSubscribed = false;
	const isSelf = locals.user?.id === profile.id;
	if (locals.user && !isSelf) {
		const sub = await getSubscription(locals.user.id, profile.id).catch(() => null);
		isSubscribed = !!sub;
	}

	// Load public library + currently reading in parallel
	const [library, currentlyReading] = await Promise.all([
		getUserPublicLibrary(profile.id).catch((e) => {
			log.error('users/profile', 'getUserPublicLibrary failed', { username, err: String(e) });
			return [] as Awaited<ReturnType<typeof getUserPublicLibrary>>;
		}),
		getUserCurrentlyReading(profile.id).catch((e) => {
			log.error('users/profile', 'getUserCurrentlyReading failed', { username, err: String(e) });
			return [] as Awaited<ReturnType<typeof getUserCurrentlyReading>>;
		})
	]);

	return {
		profile: {
			id: profile.id,
			username: profile.username,
			created: profile.created,
			followerCount: profile.followerCount,
			followingCount: profile.followingCount
		},
		avatarUrl,
		isSubscribed,
		isSelf,
		isLoggedIn: !!locals.user,
		library,
		currentlyReading
	};
};
