/**
 * API endpoint for downloading a single event as an .ics file
 * Requires authentication for non-public events
 */

import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { generateSingleEventIcal } from '$lib/server/ical';

export const GET: RequestHandler = async ({ params, locals, url }) => {
	const eventId = params.id;

	// Get user session
	const { member } = await locals.safeGetSession();

	// Fetch the event
	const { data: event, error: fetchError } = await locals.supabase
		.from('events')
		.select(`
			id,
			title,
			description,
			start_datetime,
			end_datetime,
			location,
			location_url,
			timezone,
			status,
			visibility,
			all_day,
			event_type:event_types(name)
		`)
		.eq('id', eventId)
		.single();

	if (fetchError || !event) {
		throw error(404, 'Event not found');
	}

	// Check visibility permissions
	const canView = checkVisibility(event.visibility, member?.role);
	if (!canView) {
		throw error(403, 'You do not have permission to view this event');
	}

	// Generate iCal content
	const baseUrl = url.origin || 'https://monacousa.org';
	const icalContent = generateSingleEventIcal(
		{
			id: event.id,
			title: event.title,
			description: event.description || undefined,
			start_datetime: event.start_datetime,
			end_datetime: event.end_datetime,
			location: event.location,
			location_url: event.location_url,
			timezone: event.timezone || 'Europe/Monaco',
			status: event.status as 'published' | 'cancelled' | 'draft',
			event_type_name: (event.event_type as { name: string } | null)?.name,
			organizer_name: 'Monaco USA',
			organizer_email: 'events@monacousa.org',
			all_day: event.all_day || false
		},
		baseUrl
	);

	// Generate filename
	const sanitizedTitle = event.title
		.toLowerCase()
		.replace(/[^a-z0-9]+/g, '-')
		.replace(/^-|-$/g, '')
		.substring(0, 50);
	const filename = `monaco-usa-${sanitizedTitle}.ics`;

	return new Response(icalContent, {
		headers: {
			'Content-Type': 'text/calendar; charset=utf-8',
			'Content-Disposition': `attachment; filename="${filename}"`,
			'Cache-Control': 'no-cache, no-store, must-revalidate'
		}
	});
};

function checkVisibility(visibility: string, role?: string): boolean {
	switch (visibility) {
		case 'public':
			return true;
		case 'members':
			return !!role; // Any authenticated member
		case 'board':
			return role === 'board' || role === 'admin';
		case 'admin':
			return role === 'admin';
		default:
			return false;
	}
}
