import type { PageServerLoad } from './$types';
import { getRecentAuditLogs } from '$lib/server/audit';

export const load: PageServerLoad = async ({ locals }) => {
	// Get all members with dues info for stats
	const { data: members } = await locals.supabase
		.from('members_with_dues')
		.select('*');

	// Get recent payments (this month and last month)
	const now = new Date();
	const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
	const startOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);

	const { data: recentPayments } = await locals.supabase
		.from('dues_payments')
		.select(`
			*,
			member:members(first_name, last_name, email)
		`)
		.gte('payment_date', startOfLastMonth.toISOString())
		.order('payment_date', { ascending: false });

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

	const { data: upcomingEvents } = await locals.supabase
		.from('events_with_counts')
		.select('*')
		.eq('status', 'published')
		.gte('start_datetime', now.toISOString())
		.lte('start_datetime', thirtyDaysFromNow.toISOString())
		.order('start_datetime', { ascending: true })
		.limit(5);

	// Get recent audit logs
	const { logs: auditLogs } = await getRecentAuditLogs(20);

	// Calculate member stats
	const memberStats = {
		total: members?.length || 0,
		byRole: {
			admin: members?.filter(m => m.role === 'admin').length || 0,
			board: members?.filter(m => m.role === 'board').length || 0,
			member: members?.filter(m => m.role === 'member').length || 0
		},
		byDuesStatus: {
			current: members?.filter(m => m.dues_status === 'current').length || 0,
			due_soon: members?.filter(m => m.dues_status === 'due_soon').length || 0,
			overdue: members?.filter(m => m.dues_status === 'overdue').length || 0,
			never_paid: members?.filter(m => m.dues_status === 'never_paid').length || 0
		}
	};

	// Calculate revenue stats
	const thisMonthPayments = recentPayments?.filter(p =>
		new Date(p.payment_date) >= startOfMonth
	) || [];
	const lastMonthPayments = recentPayments?.filter(p =>
		new Date(p.payment_date) >= startOfLastMonth &&
		new Date(p.payment_date) < startOfMonth
	) || [];

	const revenueStats = {
		thisMonth: thisMonthPayments.reduce((sum, p) => sum + (p.amount || 0), 0),
		lastMonth: lastMonthPayments.reduce((sum, p) => sum + (p.amount || 0), 0),
		thisMonthCount: thisMonthPayments.length,
		lastMonthCount: lastMonthPayments.length
	};

	// Get recent payments for display
	const { data: latestPayments } = await locals.supabase
		.from('dues_payments')
		.select(`
			*,
			member:members(first_name, last_name, email),
			recorder:members!dues_payments_recorded_by_fkey(first_name, last_name)
		`)
		.order('created_at', { ascending: false })
		.limit(5);

	return {
		memberStats,
		revenueStats,
		upcomingEvents: upcomingEvents || [],
		recentPayments: latestPayments || [],
		auditLogs: auditLogs || [],
		overdueMembers: members?.filter(m => m.dues_status === 'overdue').slice(0, 5) || []
	};
};
