/**
 * Cron API Endpoint for Automated Event Reminders
 *
 * This endpoint should be called hourly by an external cron service
 * to send reminder emails to members 24 hours before events.
 *
 * Security: Requires CRON_SECRET header for authentication
 *
 * Example cron setup (hourly):
 * 0 * * * * curl -X POST https://yourdomain.com/api/cron/event-reminders \
 *   -H "Authorization: Bearer YOUR_CRON_SECRET"
 */

import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { env } from '$env/dynamic/private';
import {
	getEventReminderSettings,
	getEventsNeedingReminders,
	sendEventReminders,
	getEventReminderStats
} from '$lib/server/event-reminders';

const CRON_SECRET = env.CRON_SECRET;

export const POST: RequestHandler = async ({ request, url }) => {
	// Verify cron secret
	const authHeader = request.headers.get('authorization');
	const token = authHeader?.replace('Bearer ', '');

	if (!CRON_SECRET) {
		console.error('CRON_SECRET not configured');
		return json({ error: 'Server not configured for cron jobs' }, { status: 500 });
	}

	if (token !== CRON_SECRET) {
		return json({ error: 'Unauthorized' }, { status: 401 });
	}

	const baseUrl = url.origin || env.SITE_URL || 'https://monacousa.org';
	const dryRun = url.searchParams.get('dry_run') === 'true';

	try {
		// Load settings
		const settings = await getEventReminderSettings();

		const results = {
			timestamp: new Date().toISOString(),
			dryRun,
			settings: {
				event_reminders_enabled: settings.event_reminders_enabled,
				event_reminder_hours_before: settings.event_reminder_hours_before
			},
			eligible: 0,
			sent: 0,
			skipped: 0,
			errors: [] as string[],
			reminders: [] as Array<{
				eventId: string;
				eventTitle: string;
				memberId: string;
				memberName: string;
				email: string;
				status: string;
				error?: string;
			}>
		};

		if (!settings.event_reminders_enabled) {
			return json({
				...results,
				message: 'Event reminders are disabled'
			});
		}

		// Get events needing reminders
		const eventsNeeding = await getEventsNeedingReminders();
		results.eligible = eventsNeeding.length;

		if (dryRun) {
			// Just show what would be sent
			results.reminders = eventsNeeding.map(e => ({
				eventId: e.event_id,
				eventTitle: e.event_title,
				memberId: e.member_id,
				memberName: `${e.first_name} ${e.last_name}`,
				email: e.email,
				status: 'would_send'
			}));
			return json(results);
		}

		// Send the reminders
		if (eventsNeeding.length > 0) {
			const sendResult = await sendEventReminders(baseUrl);
			results.sent = sendResult.sent;
			results.skipped = sendResult.skipped;
			results.errors = sendResult.errors;
			results.reminders = sendResult.reminders;
		}

		return json(results);
	} catch (error) {
		console.error('Event reminders cron job error:', error);
		const errorMessage = error instanceof Error ? error.message : 'Unknown error';
		return json(
			{
				error: 'Internal server error',
				message: errorMessage,
				timestamp: new Date().toISOString()
			},
			{ status: 500 }
		);
	}
};

/**
 * GET endpoint for checking status and getting preview of pending reminders
 */
export const GET: RequestHandler = async ({ request }) => {
	// Verify cron secret
	const authHeader = request.headers.get('authorization');
	const token = authHeader?.replace('Bearer ', '');

	if (!CRON_SECRET || token !== CRON_SECRET) {
		return json({ error: 'Unauthorized' }, { status: 401 });
	}

	try {
		const settings = await getEventReminderSettings();
		const eventsNeeding = await getEventsNeedingReminders();
		const stats = await getEventReminderStats();

		const preview = {
			timestamp: new Date().toISOString(),
			settings: {
				event_reminders_enabled: settings.event_reminders_enabled,
				event_reminder_hours_before: settings.event_reminder_hours_before
			},
			pendingReminders: eventsNeeding.length,
			pendingDetails: eventsNeeding.map(e => ({
				eventId: e.event_id,
				eventTitle: e.event_title,
				eventStart: e.start_datetime,
				memberName: `${e.first_name} ${e.last_name}`,
				email: e.email,
				guestCount: e.guest_count
			})),
			stats
		};

		return json(preview);
	} catch (error) {
		console.error('Event reminders preview error:', error);
		const errorMessage = error instanceof Error ? error.message : 'Unknown error';
		return json({ error: 'Internal server error', message: errorMessage }, { status: 500 });
	}
};
