import { fail } from '@sveltejs/kit';
import { emailService } from '$lib/services/email';
import type { Actions } from './$types';

export const actions = {
	default: async ({ request }) => {
		const formData = await request.formData();
		const name = formData.get('name') as string;
		const email = formData.get('email') as string;
		const subject = formData.get('subject') as string;
		const message = formData.get('message') as string;

		if (!name || !email || !subject || !message) {
			return fail(400, { error: 'All fields are required' });
		}

		const htmlBody = `
			<p><strong>From:</strong> ${name} &lt;${email}&gt;</p>
			<p><strong>Subject:</strong> ${subject}</p>
			<hr />
			<p>${message.replace(/\n/g, '<br />')}</p>
		`.trim();

		const { error } = await emailService.sendEmail(
			{
				to: ['service@nexusclean.net'],
				subject: `Contact Form: ${subject}`,
				body: htmlBody,
				fromName: 'Nexus Dispatch'
			},
			'dispatch@nexusclean.net'
		);

		if (error) {
			console.error('Email API error:', error);
			return fail(500, { error: 'Failed to send message. Please try again.' });
		}

		return { success: true };
	}
} satisfies Actions;
