import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import {
	listUserSessions,
	getUserByUsername,
	getUserStats,
	allProgress,
	getBooksBySlugs
} from '$lib/server/pocketbase';
import { resolveAvatarUrl } from '$lib/server/minio';
import { log } from '$lib/server/logger';

export const load: PageServerLoad = async ({ locals }) => {
	if (!locals.user) {
		redirect(302, '/login');
	}

	let sessions: Awaited<ReturnType<typeof listUserSessions>> = [];
	let email: string | null = null;
	let polarCustomerId: string | null = null;
	let stats: Awaited<ReturnType<typeof getUserStats>> | null = null;

	// Fetch avatar — MinIO first, fall back to OAuth provider picture
	let avatarUrl: string | null = null;
	try {
		const record = await getUserByUsername(locals.user.username);
		avatarUrl = await resolveAvatarUrl(locals.user.id, record?.avatar_url);
		email = record?.email ?? null;
		polarCustomerId = record?.polar_customer_id ?? null;
	} catch (e) {
		log.warn('profile', 'avatar fetch failed (non-fatal)', { err: String(e) });
	}

	try {
		[sessions, stats] = await Promise.all([
			listUserSessions(locals.user.id),
			getUserStats(locals.sessionId, locals.user.id)
		]);
	} catch (e) {
		log.warn('profile', 'load failed (non-fatal)', { err: String(e) });
	}

	// Reading history — last 50 progress entries with book metadata
	let history: { slug: string; chapter: number; updated: string; title: string; cover: string | null }[] = [];
	try {
		const progress = await allProgress(locals.sessionId, locals.user.id);
		const recent = progress.slice(0, 50);
		const books = await getBooksBySlugs(new Set(recent.map((p) => p.slug)));
		const bookMap = new Map(books.map((b) => [b.slug, b]));
		history = recent.map((p) => ({
			slug: p.slug,
			chapter: p.chapter,
			updated: p.updated,
			title: bookMap.get(p.slug)?.title ?? p.slug,
			cover: bookMap.get(p.slug)?.cover ?? null
		}));
	} catch (e) {
		log.warn('profile', 'history fetch failed (non-fatal)', { err: String(e) });
	}

	return {
		user: locals.user,
		avatarUrl,
		email,
		polarCustomerId,
		stats: stats ?? {
			totalChaptersRead: 0, booksReading: 0, booksCompleted: 0,
			booksPlanToRead: 0, booksDropped: 0, topGenres: [],
			avgRatingGiven: 0, streak: 0
		},
		sessions: sessions.map((s) => ({
			id: s.id,
			user_agent: s.user_agent,
			ip: s.ip,
			created_at: s.created_at,
			last_seen: s.last_seen,
			is_current: s.session_id === locals.user!.authSessionId
		})),
		history
	};
};
