import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { supabaseAdmin } from '$lib/server/supabase';
import { env } from '$env/dynamic/private';

export const load: PageServerLoad = async () => {
	// Load recent cron execution logs
	const { data: logs } = await supabaseAdmin
		.from('cron_execution_logs')
		.select('*')
		.order('started_at', { ascending: false })
		.limit(50);

	return {
		cronLogs: logs || []
	};
};

export const actions: Actions = {
	runDuesReminders: async ({ url }) => {
		const cronSecret = env.CRON_SECRET;
		if (!cronSecret) {
			return fail(500, { error: 'CRON_SECRET not configured' });
		}

		// Log the execution start
		const { data: logEntry } = await supabaseAdmin
			.from('cron_execution_logs')
			.insert({
				job_name: 'dues-reminders',
				status: 'running',
				triggered_by: 'admin-manual'
			})
			.select()
			.single();

		try {
			const baseUrl = url.origin || env.SITE_URL || 'https://monacousa.org';
			const response = await fetch(`${baseUrl}/api/cron/dues-reminders`, {
				method: 'POST',
				headers: {
					'Authorization': `Bearer ${cronSecret}`
				}
			});

			const result = await response.json();

			// Update log entry
			if (logEntry) {
				await supabaseAdmin
					.from('cron_execution_logs')
					.update({
						status: response.ok ? 'completed' : 'failed',
						completed_at: new Date().toISOString(),
						duration_ms: Date.now() - new Date(logEntry.started_at).getTime(),
						result,
						error_message: response.ok ? null : result.error
					})
					.eq('id', logEntry.id);
			}

			if (!response.ok) {
				return fail(500, { error: result.error || 'Cron job failed' });
			}

			return { success: `Dues reminders completed. Sent: ${result.summary?.totalRemindersSent || 0}` };
		} catch (error) {
			if (logEntry) {
				await supabaseAdmin
					.from('cron_execution_logs')
					.update({
						status: 'failed',
						completed_at: new Date().toISOString(),
						duration_ms: Date.now() - new Date(logEntry.started_at).getTime(),
						error_message: error instanceof Error ? error.message : 'Unknown error'
					})
					.eq('id', logEntry.id);
			}
			return fail(500, { error: error instanceof Error ? error.message : 'Failed to run cron job' });
		}
	},

	runEventReminders: async ({ url }) => {
		const cronSecret = env.CRON_SECRET;
		if (!cronSecret) {
			return fail(500, { error: 'CRON_SECRET not configured' });
		}

		const { data: logEntry } = await supabaseAdmin
			.from('cron_execution_logs')
			.insert({
				job_name: 'event-reminders',
				status: 'running',
				triggered_by: 'admin-manual'
			})
			.select()
			.single();

		try {
			const baseUrl = url.origin || env.SITE_URL || 'https://monacousa.org';
			const response = await fetch(`${baseUrl}/api/cron/event-reminders`, {
				method: 'POST',
				headers: {
					'Authorization': `Bearer ${cronSecret}`
				}
			});

			const result = await response.json();

			if (logEntry) {
				await supabaseAdmin
					.from('cron_execution_logs')
					.update({
						status: response.ok ? 'completed' : 'failed',
						completed_at: new Date().toISOString(),
						duration_ms: Date.now() - new Date(logEntry.started_at).getTime(),
						result,
						error_message: response.ok ? null : result.error
					})
					.eq('id', logEntry.id);
			}

			if (!response.ok) {
				return fail(500, { error: result.error || 'Cron job failed' });
			}

			return { success: `Event reminders completed. Sent: ${result.sent || 0}` };
		} catch (error) {
			if (logEntry) {
				await supabaseAdmin
					.from('cron_execution_logs')
					.update({
						status: 'failed',
						completed_at: new Date().toISOString(),
						duration_ms: Date.now() - new Date(logEntry.started_at).getTime(),
						error_message: error instanceof Error ? error.message : 'Unknown error'
					})
					.eq('id', logEntry.id);
			}
			return fail(500, { error: error instanceof Error ? error.message : 'Failed to run cron job' });
		}
	}
};
