import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { supabaseAdmin } from '$lib/server/supabase';
import { arrayToCSV, csvResponse } from '$lib/server/csv';

export const GET: RequestHandler = async ({ params, locals, url }) => {
	const { member } = await locals.safeGetSession();

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

	const reportType = params.type;
	const year = parseInt(url.searchParams.get('year') || new Date().getFullYear().toString());
	const today = new Date().toISOString().split('T')[0];

	switch (reportType) {
		case 'membership':
			return await exportMembership();
		case 'payments':
			return await exportPayments(year);
		case 'events':
			return await exportEvents(year);
		default:
			throw error(400, 'Invalid report type');
	}

	async function exportMembership(): Promise<Response> {
		const { data: members } = await supabaseAdmin
			.from('members_with_dues')
			.select('*')
			.order('last_name', { ascending: true });

		const rows = (members || []).map((m: any) => ({
			member_id: m.member_id,
			first_name: m.first_name,
			last_name: m.last_name,
			email: m.email,
			phone: m.phone || '',
			status: m.status_display_name || '',
			member_type: m.membership_type_name || '',
			role: m.role,
			dues_status: m.dues_status,
			member_since: m.member_since || ''
		}));

		const csv = arrayToCSV(rows, [
			{ key: 'member_id', header: 'Member ID' },
			{ key: 'first_name', header: 'First Name' },
			{ key: 'last_name', header: 'Last Name' },
			{ key: 'email', header: 'Email' },
			{ key: 'phone', header: 'Phone' },
			{ key: 'status', header: 'Status' },
			{ key: 'member_type', header: 'Member Type' },
			{ key: 'role', header: 'Role' },
			{ key: 'dues_status', header: 'Dues Status' },
			{ key: 'member_since', header: 'Member Since' }
		]);

		return csvResponse(csv, `membership-report-${today}.csv`);
	}

	async function exportPayments(yr: number): Promise<Response> {
		const startOfYear = `${yr}-01-01`;
		const endOfYear = `${yr}-12-31`;

		const { data: payments } = await supabaseAdmin
			.from('dues_payments')
			.select(`
				*,
				member:members(first_name, last_name, email, member_id)
			`)
			.gte('payment_date', startOfYear)
			.lte('payment_date', endOfYear)
			.order('payment_date', { ascending: false });

		const rows = (payments || []).map((p: any) => ({
			payment_date: p.payment_date,
			member_id: p.member?.member_id || '',
			member_name: p.member ? `${p.member.first_name} ${p.member.last_name}` : '',
			email: p.member?.email || '',
			amount: p.amount,
			payment_method: p.payment_method || '',
			status: p.status || 'completed',
			reference: p.reference || '',
			notes: p.notes || ''
		}));

		const csv = arrayToCSV(rows, [
			{ key: 'payment_date', header: 'Payment Date' },
			{ key: 'member_id', header: 'Member ID' },
			{ key: 'member_name', header: 'Member Name' },
			{ key: 'email', header: 'Email' },
			{ key: 'amount', header: 'Amount' },
			{ key: 'payment_method', header: 'Method' },
			{ key: 'status', header: 'Status' },
			{ key: 'reference', header: 'Reference' },
			{ key: 'notes', header: 'Notes' }
		]);

		return csvResponse(csv, `payments-report-${yr}.csv`);
	}

	async function exportEvents(yr: number): Promise<Response> {
		const startOfYear = `${yr}-01-01T00:00:00`;
		const endOfYear = `${yr}-12-31T23:59:59`;

		const { data: events } = await supabaseAdmin
			.from('events_with_counts')
			.select('*')
			.gte('start_datetime', startOfYear)
			.lte('start_datetime', endOfYear)
			.order('start_datetime', { ascending: false });

		const rows = (events || []).map((e: any) => ({
			date: e.start_datetime ? new Date(e.start_datetime).toLocaleDateString('en-US') : '',
			title: e.title,
			type: e.event_type_name || 'General',
			location: e.location || '',
			rsvp_count: e.total_attendees || 0,
			max_capacity: e.max_attendees || 'Unlimited',
			waitlist: e.waitlist_count || 0,
			status: e.status || ''
		}));

		const csv = arrayToCSV(rows, [
			{ key: 'date', header: 'Date' },
			{ key: 'title', header: 'Title' },
			{ key: 'type', header: 'Type' },
			{ key: 'location', header: 'Location' },
			{ key: 'rsvp_count', header: 'RSVP Count' },
			{ key: 'max_capacity', header: 'Max Capacity' },
			{ key: 'waitlist', header: 'Waitlist' },
			{ key: 'status', header: 'Status' }
		]);

		return csvResponse(csv, `events-report-${yr}.csv`);
	}
};
