import { error, fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals, params }) => {
	// Fetch the event (only public events)
	const { data: event } = await locals.supabase
		.from('events_with_counts')
		.select('*')
		.eq('id', params.id)
		.eq('visibility', 'public')
		.eq('status', 'published')
		.single();

	if (!event) {
		throw error(404, 'Event not found or not publicly accessible');
	}

	return {
		event
	};
};

export const actions: Actions = {
	rsvp: async ({ request, locals, params }) => {
		const formData = await request.formData();
		const fullName = (formData.get('full_name') as string)?.trim();
		const email = (formData.get('email') as string)?.trim().toLowerCase();
		const phone = (formData.get('phone') as string)?.trim() || null;
		const guestCount = parseInt(formData.get('guest_count') as string) || 0;

		// Validation
		if (!fullName || fullName.length < 2) {
			return fail(400, { error: 'Please enter your full name' });
		}

		if (!email) {
			return fail(400, { error: 'Please enter your email address' });
		}

		// Email validation
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(email)) {
			return fail(400, { error: 'Please enter a valid email address' });
		}

		// Fetch the event to check capacity
		const { data: event } = await locals.supabase
			.from('events_with_counts')
			.select('*')
			.eq('id', params.id)
			.eq('visibility', 'public')
			.eq('status', 'published')
			.single();

		if (!event) {
			return fail(404, { error: 'Event not found' });
		}

		// Validate guest count
		if (event.max_guests_per_member !== null && guestCount > event.max_guests_per_member) {
			return fail(400, {
				error: `Maximum ${event.max_guests_per_member} guest${event.max_guests_per_member === 1 ? '' : 's'} allowed`
			});
		}

		// Check if this email already RSVP'd
		const { data: existingRsvp } = await locals.supabase
			.from('event_rsvps_public')
			.select('id')
			.eq('event_id', params.id)
			.eq('email', email)
			.single();

		if (existingRsvp) {
			return fail(400, { error: 'This email has already registered for this event' });
		}

		// Check if event is full
		const totalAttending = event.total_attendees + 1 + guestCount;
		const isFull = event.max_attendees && totalAttending > event.max_attendees;

		// Create public RSVP
		const { error: rsvpError } = await locals.supabase.from('event_rsvps_public').insert({
			event_id: params.id,
			full_name: fullName,
			email,
			phone,
			status: isFull ? 'waitlist' : 'confirmed',
			guest_count: guestCount,
			payment_status: event.is_paid ? 'pending' : 'not_required',
			payment_amount: event.is_paid ? event.non_member_price * (1 + guestCount) : null
		});

		if (rsvpError) {
			console.error('Public RSVP error:', rsvpError);
			return fail(500, { error: 'Failed to submit RSVP. Please try again.' });
		}

		return {
			success: isFull
				? 'You have been added to the waitlist. We will notify you if a spot opens up.'
				: 'Registration successful! We look forward to seeing you at the event.'
		};
	}
};
