/**
 * API endpoint for subscribing to Monaco USA events calendar feed
 * Returns iCal feed of upcoming events
 *
 * Usage:
 * - /api/calendar/feed - Public events only (no auth required)
 * - /api/calendar/feed?token=xxx - Member events with auth token
 *
 * Subscribe URL: webcal://yourdomain.com/api/calendar/feed
 */

import type { RequestHandler } from './$types';
import { generateCalendarFeed, type ICalEvent } from '$lib/server/ical';
import { supabaseAdmin } from '$lib/server/supabase';

export const GET: RequestHandler = async ({ url, locals }) => {
	const token = url.searchParams.get('token');
	const includePrivate = url.searchParams.get('private') === 'true';

	// Determine visibility level based on authentication
	let visibilityLevels = ['public'];
	let calendarName = 'Monaco USA Public Events';

	// Check if user is authenticated (via session or token)
	const { member } = await locals.safeGetSession();

	if (member) {
		// Authenticated user - include member events
		visibilityLevels = getVisibilityLevels(member.role);
		calendarName = 'Monaco USA Events';
	} else if (token) {
		// Token-based access (for calendar subscriptions)
		// Verify the token against a member's calendar token
		const { data: memberWithToken } = await supabaseAdmin
			.from('members')
			.select('id, role')
			.eq('calendar_token', token)
			.single();

		if (memberWithToken) {
			visibilityLevels = getVisibilityLevels(memberWithToken.role);
			calendarName = 'Monaco USA Events';
		}
	}

	// Fetch upcoming events
	const now = new Date();
	const threeMonthsFromNow = new Date(now.getTime() + 90 * 24 * 60 * 60 * 1000);

	const { data: events, error: fetchError } = await supabaseAdmin
		.from('events')
		.select(`
			id,
			title,
			description,
			start_datetime,
			end_datetime,
			location,
			location_url,
			timezone,
			status,
			visibility,
			all_day,
			event_type:event_types(name)
		`)
		.in('visibility', visibilityLevels)
		.eq('status', 'published')
		.gte('start_datetime', now.toISOString())
		.lte('start_datetime', threeMonthsFromNow.toISOString())
		.order('start_datetime', { ascending: true });

	if (fetchError) {
		console.error('Error fetching events for feed:', fetchError);
		return new Response('Error fetching events', { status: 500 });
	}

	// Convert to ICalEvent format
	const baseUrl = url.origin || 'https://monacousa.org';
	const icalEvents: ICalEvent[] = (events || []).map(event => ({
		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
	}));

	// Generate iCal feed
	const icalContent = generateCalendarFeed(icalEvents, calendarName, baseUrl);

	return new Response(icalContent, {
		headers: {
			'Content-Type': 'text/calendar; charset=utf-8',
			'Cache-Control': 'public, max-age=3600', // Cache for 1 hour
			'X-WR-CALNAME': calendarName
		}
	});
};

function getVisibilityLevels(role?: string): string[] {
	switch (role) {
		case 'admin':
			return ['public', 'members', 'board', 'admin'];
		case 'board':
			return ['public', 'members', 'board'];
		case 'member':
		default:
			return ['public', 'members'];
	}
}
