import { z } from 'zod'
import { Resend } from 'resend'

/**
 * Send email through Resend API
 *
 * @param prevState
 * @param formData
 */
export async function send(prevState: any, formData: FormData) {

  const schema = z.object({
    email: z.string().email(),
    subject: z.string(),
    name: z.string(),
    message: z.string()
  });

  const validatedFields = schema.safeParse({
    name: formData.get("name"),
    email: formData.get("email"),
    subject: formData.get("subject"),
    message: formData.get("message"),
  })

  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      message: "Nicht alle Felder waren gültig"
    }
  }

  try {
    const resend = new Resend(process.env.RESEND_API_KEY);
    await resend.emails.send({
      from: 'kontakt@resend.dev',
      replyTo: validatedFields.data.email,
      to: 'buero@sankt-clara.de',
      subject: `Über Kontaktformular: ${validatedFields.data.subject}`,
      text: `Nachricht von ${validatedFields.data.name}: \n\n ${validatedFields.data.message}`
    });
  } catch (e) {
    return { message: "Fehler beim senden der Nachricht." };
  }

  return {
    message: "Ihre Nachricht wurde erfolgreich übermittelt"
  }

}