import { fail, error, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { escapeHtml, sanitizeRichText } from '$lib/server/sanitize';
import { logEventAction } from '$lib/server/audit';

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

	if (!member || (member.role !== 'board' && member.role !== 'admin')) {
		throw redirect(303, '/dashboard');
	}

	// Fetch the event
	const { data: event } = await locals.supabase
		.from('events')
		.select('*')
		.eq('id', params.id)
		.single();

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

	// Load event types
	const { data: eventTypes } = await locals.supabase
		.from('event_types')
		.select('*')
		.eq('is_active', true)
		.order('sort_order', { ascending: true });

	return {
		event,
		eventTypes: eventTypes || []
	};
};

export const actions: Actions = {
	update: async ({ request, locals, params }) => {
		const { member } = await locals.safeGetSession();

		if (!member || (member.role !== 'board' && member.role !== 'admin')) {
			return fail(403, { error: 'You do not have permission to edit events' });
		}

		const formData = await request.formData();

		const title = escapeHtml(formData.get('title') as string);
		const description = sanitizeRichText(formData.get('description') as string || '');
		const eventTypeId = formData.get('event_type_id') as string;
		const startDate = formData.get('start_date') as string;
		const startTime = formData.get('start_time') as string;
		const endDate = formData.get('end_date') as string;
		const endTime = formData.get('end_time') as string;
		const location = formData.get('location') as string;
		const locationUrl = formData.get('location_url') as string;
		const maxAttendees = formData.get('max_attendees') as string;
		const maxGuests = formData.get('max_guests_per_member') as string;
		const isPaid = formData.get('is_paid') === 'true';
		const memberPrice = formData.get('member_price') as string;
		const nonMemberPrice = formData.get('non_member_price') as string;
		const visibility = formData.get('visibility') as string;
		const status = formData.get('status') as string;
		const rsvpDeadlineEnabled = formData.get('rsvp_deadline_enabled') === 'true';
		const rsvpDeadlineDate = formData.get('rsvp_deadline_date') as string;
		const rsvpDeadlineTime = formData.get('rsvp_deadline_time') as string;

		// Validation
		if (!title || !startDate || !startTime || !endDate || !endTime) {
			return fail(400, { error: 'Title, start date/time, and end date/time are required' });
		}

		// Construct datetime strings
		const startDatetime = `${startDate}T${startTime}:00`;
		const endDatetime = `${endDate}T${endTime}:00`;

		// Validate end is after start
		if (new Date(endDatetime) <= new Date(startDatetime)) {
			return fail(400, { error: 'End date/time must be after start date/time' });
		}

		const { error: updateError } = await locals.supabase
			.from('events')
			.update({
				title,
				description: description || null,
				event_type_id: eventTypeId || null,
				start_datetime: startDatetime,
				end_datetime: endDatetime,
				location: location || null,
				location_url: locationUrl || null,
				max_attendees: maxAttendees ? parseInt(maxAttendees) : null,
				max_guests_per_member: maxGuests ? parseInt(maxGuests) : 1,
				is_paid: isPaid,
				member_price: isPaid && memberPrice ? parseFloat(memberPrice) : 0,
				non_member_price: isPaid && nonMemberPrice ? parseFloat(nonMemberPrice) : 0,
				visibility: visibility || 'members',
				status: status || 'published',
				rsvp_deadline_enabled: rsvpDeadlineEnabled,
				rsvp_deadline: rsvpDeadlineEnabled && rsvpDeadlineDate && rsvpDeadlineTime
					? `${rsvpDeadlineDate}T${rsvpDeadlineTime}:00`
					: null,
				updated_at: new Date().toISOString()
			})
			.eq('id', params.id);

		if (updateError) {
			console.error('Event update error:', updateError);
			return fail(500, { error: 'Failed to update event. Please try again.' });
		}

		logEventAction(
			status === 'cancelled' ? 'cancel' : 'update',
			{ id: member.id, email: member.email! },
			{ id: params.id, title },
			{ status }
		);

		return { success: 'Event updated successfully!' };
	},

	delete: async ({ locals, params }) => {
		const { member } = await locals.safeGetSession();

		if (!member || member.role !== 'admin') {
			return fail(403, { error: 'Only admins can delete events' });
		}

		const { error: deleteError } = await locals.supabase
			.from('events')
			.delete()
			.eq('id', params.id);

		if (deleteError) {
			console.error('Event deletion error:', deleteError);
			return fail(500, { error: 'Failed to delete event. Please try again.' });
		}

		logEventAction('delete',
			{ id: member.id, email: member.email! },
			{ id: params.id },
			{ deleted_by_admin: true }
		);

		throw redirect(303, '/board/events?deleted=true');
	}
};
