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

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

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

	// Load recent notifications with member info
	const { data: notifications } = await supabaseAdmin
		.from('notifications')
		.select(`
			*,
			member:members!member_id (
				id,
				first_name,
				last_name,
				email
			)
		`)
		.order('created_at', { ascending: false })
		.limit(100);

	// Load all members for the recipient selector
	const { data: members } = await supabaseAdmin
		.from('members')
		.select('id, first_name, last_name, email, role')
		.order('last_name', { ascending: true });

	return {
		notifications: notifications || [],
		members: members || []
	};
};

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

		if (!member || member.role !== 'admin') {
			return fail(403, { error: 'Unauthorized' });
		}

		const formData = await request.formData();
		const type = formData.get('type') as string;
		const title = escapeHtml(formData.get('title') as string);
		const message = escapeHtml(formData.get('message') as string);
		const link = (formData.get('link') as string) || null;
		const recipientType = formData.get('recipient_type') as string;
		const recipientId = formData.get('recipient_id') as string;

		if (!type || !title || !message) {
			return fail(400, { error: 'Type, title, and message are required' });
		}

		// Validate type
		const validTypes = ['welcome', 'event', 'payment', 'membership', 'system', 'announcement'];
		if (!validTypes.includes(type)) {
			return fail(400, { error: 'Invalid notification type' });
		}

		let memberIds: string[] = [];

		if (recipientType === 'all') {
			// Get all member IDs
			const { data: allMembers } = await supabaseAdmin
				.from('members')
				.select('id');
			memberIds = (allMembers || []).map(m => m.id);
		} else if (recipientType === 'role') {
			const role = formData.get('role') as string;
			const { data: roleMembers } = await supabaseAdmin
				.from('members')
				.select('id')
				.eq('role', role);
			memberIds = (roleMembers || []).map(m => m.id);
		} else if (recipientType === 'single' && recipientId) {
			memberIds = [recipientId];
		} else {
			return fail(400, { error: 'Please select at least one recipient' });
		}

		if (memberIds.length === 0) {
			return fail(400, { error: 'No recipients found' });
		}

		// Create notifications for all selected members
		const notifications = memberIds.map(memberId => ({
			member_id: memberId,
			type,
			title,
			message,
			link
		}));

		const { error } = await supabaseAdmin
			.from('notifications')
			.insert(notifications);

		if (error) {
			console.error('Create notification error:', error);
			return fail(500, { error: 'Failed to create notification(s)' });
		}

		return {
			success: `Notification sent to ${memberIds.length} member${memberIds.length === 1 ? '' : 's'}!`
		};
	},

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

		if (!member || member.role !== 'admin') {
			return fail(403, { error: 'Unauthorized' });
		}

		const formData = await request.formData();
		const id = formData.get('id') as string;

		if (!id) {
			return fail(400, { error: 'Notification ID is required' });
		}

		const { error } = await supabaseAdmin
			.from('notifications')
			.delete()
			.eq('id', id);

		if (error) {
			console.error('Delete notification error:', error);
			return fail(500, { error: 'Failed to delete notification' });
		}

		return { success: 'Notification deleted' };
	}
};
