import type { PageServerLoad } from './$types';

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

	// Fetch payment history
	const { data: payments } = await locals.supabase
		.from('dues_payments')
		.select('*')
		.eq('member_id', member?.id)
		.order('payment_date', { ascending: false });

	// Fetch payment settings
	const { data: settings } = await locals.supabase
		.from('app_settings')
		.select('setting_key, setting_value')
		.eq('category', 'dues');

	// Convert settings array to object
	const paymentSettings: Record<string, string> = {};
	if (settings) {
		for (const setting of settings) {
			const key = setting.setting_key.replace('payment_', '');
			const value = setting.setting_value;
			// Handle JSON-encoded strings
			if (typeof value === 'string' && value.startsWith('"')) {
				try {
					paymentSettings[key] = JSON.parse(value);
				} catch {
					paymentSettings[key] = value;
				}
			} else {
				paymentSettings[key] = String(value);
			}
		}
	}

	return {
		payments: payments || [],
		paymentSettings
	};
};
