import { db } from '$lib/server/db';
import { character, devilFruit, arc, user } from '$lib/server/db/schema';
import { getOrCreateTodayCharacter, getTodayCharacterWinsCount } from '$lib/server/daily-character';
import type { PageServerLoad } from './$types';
import { count, eq } from 'drizzle-orm';

export const load: PageServerLoad = async () => {
	const [totalCharacters, totalDevilFruits, totalArcs, totalUsers, adminUsers, charactersInDaily] = await Promise.all([
		db.select({ count: count() }).from(character),
		db.select({ count: count() }).from(devilFruit),
		db.select({ count: count() }).from(arc),
		db.select({ count: count() }).from(user),
		db.select({ count: count() }).from(user).where(eq(user.isAdmin, true)),
		db.select({ count: count() }).from(character).where(eq(character.isInDailyMode, true))
	]);

	// Get today's daily character and count wins
	const todayCharacter = await getOrCreateTodayCharacter();
	
	let dailyCharacterWins = 0;
	if (todayCharacter) {
		dailyCharacterWins = await getTodayCharacterWinsCount(todayCharacter.id);
	}

	return {
		stats: {
			totalCharacters: totalCharacters[0].count,
			charactersInDaily: charactersInDaily[0].count,
			totalDevilFruits: totalDevilFruits[0].count,
			totalArcs: totalArcs[0].count,
			totalUsers: totalUsers[0].count,
			adminUsers: adminUsers[0].count,
			dailyCharacterWins
		}
	};
};
