import type { PageServerLoad } from './$types';
import { getVisibleLevels } from '$lib/server/visibility';

export const load: PageServerLoad = async ({ locals, parent }) => {
	const { member } = await parent();

	// Fetch upcoming events
	const { data: upcomingEvents } = await locals.supabase
		.from('events_with_counts')
		.select('*')
		.in('visibility', getVisibleLevels(member?.role))
		.eq('status', 'published')
		.gte('start_datetime', new Date().toISOString())
		.order('start_datetime', { ascending: true })
		.limit(5);

	// Fetch stats for board/admin
	let stats = null;

	if (member?.role === 'board' || member?.role === 'admin') {
		const isAdmin = member?.role === 'admin';

		// Get member counts by status
		const { data: memberCounts } = await locals.supabase
			.from('members_with_dues')
			.select('status_name, dues_status');

		const totalMembers = memberCounts?.length || 0;
		const activeMembers = memberCounts?.filter((m) => m.status_name === 'active').length || 0;
		const pendingMembers = memberCounts?.filter((m) => m.status_name === 'pending').length || 0;
		const inactiveMembers = memberCounts?.filter((m) => m.status_name === 'inactive').length || 0;
		const duesOverdue = memberCounts?.filter((m) => m.dues_status === 'overdue').length || 0;
		const duesSoon = memberCounts?.filter((m) => m.dues_status === 'due_soon').length || 0;

		// Get upcoming events count (next 30 days)
		const thirtyDaysFromNow = new Date();
		thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30);

		const { count: upcomingEventsCount } = await locals.supabase
			.from('events')
			.select('*', { count: 'exact', head: true })
			.eq('status', 'published')
			.gte('start_datetime', new Date().toISOString())
			.lte('start_datetime', thirtyDaysFromNow.toISOString());

		// Get total dues collected this year (admin only)
		let totalDuesCollected = 0;
		if (isAdmin) {
			const startOfYear = new Date(new Date().getFullYear(), 0, 1).toISOString();
			const { data: payments } = await locals.supabase
				.from('dues_payments')
				.select('amount')
				.gte('payment_date', startOfYear);

			totalDuesCollected = payments?.reduce((sum, p) => sum + (p.amount || 0), 0) || 0;
		}

		stats = {
			totalMembers,
			activeMembers,
			pendingMembers,
			inactiveMembers,
			duesOverdue,
			duesSoon,
			upcomingEventsCount: upcomingEventsCount || 0,
			totalDuesCollected
		};
	}

	return {
		upcomingEvents: upcomingEvents || [],
		stats
	};
};

