import { fail, redirect } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';

export const load: PageServerLoad = async ({ locals }) => {
	// Check admin access
	const { data: { user } } = await locals.supabase.auth.getUser();
	if (!user) throw redirect(303, '/login');

	const { data: member } = await locals.supabase
		.from('members')
		.select('role')
		.eq('id', user.id)
		.single();

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

	// Load all email templates
	const { data: templates, error } = await locals.supabase
		.from('email_templates')
		.select('*')
		.order('category', { ascending: true })
		.order('template_name', { ascending: true });

	if (error) {
		console.error('Error loading email templates:', error);
		return { templates: [] };
	}

	return { templates: templates || [] };
};

export const actions: Actions = {
	updateTemplate: async ({ request, locals }) => {
		const { data: { user } } = await locals.supabase.auth.getUser();
		if (!user) {
			return fail(401, { error: 'Unauthorized' });
		}

		// Check admin access
		const { data: member } = await locals.supabase
			.from('members')
			.select('role')
			.eq('id', user.id)
			.single();

		if (!member || !['admin', 'board'].includes(member.role)) {
			return fail(403, { error: 'Access denied' });
		}

		const formData = await request.formData();
		const template_key = formData.get('template_key') as string;
		const subject = formData.get('subject') as string;
		const body_html = formData.get('body_html') as string;
		const body_text = formData.get('body_text') as string;
		const is_active = formData.get('is_active') === 'true';

		if (!template_key) {
			return fail(400, { error: 'Template key is required' });
		}

		// Update the template
		const { error } = await locals.supabase
			.from('email_templates')
			.update({
				subject,
				body_html,
				body_text,
				is_active,
				updated_at: new Date().toISOString(),
				updated_by: user.id
			})
			.eq('template_key', template_key);

		if (error) {
			console.error('Error updating template:', error);
			return fail(500, { error: 'Failed to update template' });
		}

		return { success: true, message: 'Template updated successfully' };
	}
};
