import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { getDuesAnalytics, getDuesReportData, getReminderEffectiveness } from '$lib/server/dues';

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

	if (!member || (member.role !== 'board' && member.role !== 'admin')) {
		return { error: 'Unauthorized' };
	}

	// Load analytics data
	const analytics = await getDuesAnalytics();
	const effectiveness = await getReminderEffectiveness();

	return {
		analytics,
		effectiveness
	};
};

export const actions: Actions = {
	/**
	 * Export members report as CSV
	 */
	exportMembers: async ({ locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'Unauthorized' });
		}

		const data = await getDuesReportData();

		// Generate CSV
		const headers = [
			'Member ID',
			'Name',
			'Email',
			'Membership Type',
			'Status',
			'Dues Status',
			'Annual Dues',
			'Last Payment',
			'Due Date',
			'Days Overdue'
		];

		const rows = data.members.map((m) => [
			m.member_id,
			m.name,
			m.email,
			m.membership_type,
			m.status,
			m.dues_status,
			m.annual_dues.toFixed(2),
			m.last_payment_date || 'Never',
			m.current_due_date || 'N/A',
			m.days_overdue?.toString() || '0'
		]);

		const csv = [headers.join(','), ...rows.map((r) => r.map(escapeCSV).join(','))].join('\n');

		return {
			csv,
			filename: `dues-members-${new Date().toISOString().split('T')[0]}.csv`
		};
	},

	/**
	 * Export payments report as CSV
	 */
	exportPayments: async ({ locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'Unauthorized' });
		}

		const data = await getDuesReportData();

		// Generate CSV
		const headers = [
			'Member ID',
			'Member Name',
			'Amount',
			'Payment Date',
			'Payment Method',
			'Reference',
			'Recorded By'
		];

		const rows = data.payments.map((p) => [
			p.member_id,
			p.member_name,
			p.amount.toFixed(2),
			p.payment_date,
			p.payment_method,
			p.reference || '',
			p.recorded_by || ''
		]);

		const csv = [headers.join(','), ...rows.map((r) => r.map(escapeCSV).join(','))].join('\n');

		return {
			csv,
			filename: `dues-payments-${new Date().toISOString().split('T')[0]}.csv`
		};
	},

	/**
	 * Export overdue members report as CSV
	 */
	exportOverdue: async ({ locals }) => {
		const { member } = await locals.safeGetSession();

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'Unauthorized' });
		}

		const data = await getDuesReportData();

		// Filter to overdue only
		const overdueMembers = data.members.filter(
			(m) => m.dues_status === 'overdue' || m.dues_status === 'never_paid'
		);

		// Generate CSV
		const headers = [
			'Member ID',
			'Name',
			'Email',
			'Membership Type',
			'Dues Status',
			'Amount Owed',
			'Due Date',
			'Days Overdue'
		];

		const rows = overdueMembers.map((m) => [
			m.member_id,
			m.name,
			m.email,
			m.membership_type,
			m.dues_status,
			m.annual_dues.toFixed(2),
			m.current_due_date || 'N/A',
			m.days_overdue?.toString() || 'N/A'
		]);

		const csv = [headers.join(','), ...rows.map((r) => r.map(escapeCSV).join(','))].join('\n');

		return {
			csv,
			filename: `dues-overdue-${new Date().toISOString().split('T')[0]}.csv`
		};
	}
};

/**
 * Escape a value for CSV
 */
function escapeCSV(value: string | number): string {
	const str = String(value);
	if (str.includes(',') || str.includes('"') || str.includes('\n')) {
		return `"${str.replace(/"/g, '""')}"`;
	}
	return str;
}
