import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { supabaseAdmin } from '$lib/server/supabase';
import { sendEmail, wrapInMonacoTemplate } from '$lib/server/email';
import { escapeHtml } from '$lib/server/sanitize';
import { logAudit } from '$lib/server/audit';

export const load: PageServerLoad = async ({ locals }) => {
	// Load past bulk emails
	const { data: broadcasts } = await supabaseAdmin
		.from('bulk_emails')
		.select('*')
		.order('created_at', { ascending: false })
		.limit(20);

	// Get recipient counts for filter preview
	const { data: members } = await supabaseAdmin
		.from('members')
		.select('id, role, status')
		.not('email', 'is', null);

	const recipientCounts = {
		all: members?.length || 0,
		active: members?.filter((m: any) => m.status === 'active').length || 0,
		board: members?.filter((m: any) => m.role === 'board' || m.role === 'admin').length || 0,
		admin: members?.filter((m: any) => m.role === 'admin').length || 0
	};

	return {
		broadcasts: broadcasts || [],
		recipientCounts
	};
};

export const actions: Actions = {
	send: async ({ request, locals }) => {
		const { member, session } = await locals.safeGetSession();
		if (!member || !session) {
			return fail(401, { error: 'Not authenticated' });
		}

		const formData = await request.formData();
		const subject = (formData.get('subject') as string)?.trim();
		const body = (formData.get('body') as string)?.trim();
		const target = (formData.get('target') as string) || 'all';

		if (!subject || subject.length < 3) {
			return fail(400, { error: 'Subject must be at least 3 characters' });
		}

		if (!body || body.length < 10) {
			return fail(400, { error: 'Email body must be at least 10 characters' });
		}

		// Build recipient query
		let query = supabaseAdmin
			.from('members')
			.select('id, email, first_name, last_name, role, status');

		switch (target) {
			case 'active':
				query = query.eq('status', 'active');
				break;
			case 'board':
				query = query.in('role', ['board', 'admin']);
				break;
			case 'admin':
				query = query.eq('role', 'admin');
				break;
			default:
				// All members with email
				break;
		}

		const { data: recipients } = await query.not('email', 'is', null);

		if (!recipients || recipients.length === 0) {
			return fail(400, { error: 'No recipients match the selected filter' });
		}

		// Create bulk email record
		const { data: broadcast, error: createError } = await supabaseAdmin
			.from('bulk_emails')
			.insert({
				subject: escapeHtml(subject),
				body,
				recipient_filter: { target },
				total_recipients: recipients.length,
				status: 'sending',
				sent_by: session.user.id,
				sent_by_name: `${member.first_name} ${member.last_name}`,
				sent_at: new Date().toISOString()
			})
			.select()
			.single();

		if (createError || !broadcast) {
			return fail(500, { error: 'Failed to create broadcast record' });
		}

		// Send emails in batches
		let sentCount = 0;
		let failedCount = 0;

		// Convert newlines in body to <br> for HTML display
		const htmlBody = body.replace(/\n/g, '<br>');

		for (const recipient of recipients) {
			// Personalize the email content
			const personalizedBody = htmlBody
				.replace(/\{\{first_name\}\}/g, escapeHtml(recipient.first_name || ''))
				.replace(/\{\{last_name\}\}/g, escapeHtml(recipient.last_name || ''))
				.replace(/\{\{email\}\}/g, escapeHtml(recipient.email || ''));

			const emailContent = `
				<p style="margin: 0 0 16px 0; color: #334155; line-height: 1.6;">Hi ${escapeHtml(recipient.first_name || 'Member')},</p>
				<div style="color: #334155; line-height: 1.6;">${personalizedBody}</div>
			`;

			const result = await sendEmail({
				to: recipient.email,
				subject,
				html: wrapInMonacoTemplate({
					title: subject,
					content: emailContent
				}),
				recipientId: recipient.id,
				recipientName: `${recipient.first_name} ${recipient.last_name}`,
				emailType: 'announcement'
			});

			if (result.success) {
				sentCount++;
			} else {
				failedCount++;
			}
		}

		// Update broadcast record with results
		await supabaseAdmin
			.from('bulk_emails')
			.update({
				sent_count: sentCount,
				failed_count: failedCount,
				status: failedCount === recipients.length ? 'failed' : 'completed',
				completed_at: new Date().toISOString()
			})
			.eq('id', broadcast.id);

		// Audit log
		logAudit({
			action: 'email.send',
			resourceType: 'settings',
			resourceId: broadcast.id,
			userId: session.user.id,
			userEmail: member.email,
			details: {
				subject,
				target,
				totalRecipients: recipients.length,
				sent: sentCount,
				failed: failedCount
			}
		});

		return {
			success: `Broadcast sent! ${sentCount} delivered, ${failedCount} failed out of ${recipients.length} recipients.`
		};
	}
};
