"use server"

import { z } from 'zod'
import { Resend } from 'resend'
import { isSpam } from '@/utils/detectSpam'

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

  console.log('[ServerAction] send() entered', {
    toEmail,
    formKeys: [...formData.keys()],
  })

  const schema = z.object({
    email: z.email().max(100),
    subject: z.string().max(150),
    name: z.string().max(100),
    message: z.string().max(3000).min(30)
  });

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

  if (!validatedFields.success) {
    console.log('[ServerAction] Validation failed', validatedFields.error.flatten().fieldErrors)
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      message: "Nicht alle Felder waren gültig"
    }
  }

  console.log('[ServerAction] Validation passed, checking spam')

  if (isSpam(validatedFields.data.message)) {
    console.log('[ServerAction] Spam detected')
    return {
      message: "Ihre Nachricht wurde als unerwünschte Werbung eingestuft und nicht gesendet."
    }
  }

  console.log('[ServerAction] Sending email via Resend')

  try {
    const resend = new Resend(process.env.RESEND_API_KEY);
    await resend.emails.send({
      from: 'noreply@dreikoenige.berlin',
      replyTo: validatedFields.data.email,
      to: toEmail,
      subject: `Über Kontaktformular: ${validatedFields.data.subject}`,
      text: `Nachricht von ${validatedFields.data.name} (${validatedFields.data.email}): \n\n ${validatedFields.data.message}`
    });
  } catch (e) {
    console.error('[ServerAction] Resend error:', e)
    return { message: "Fehler beim senden der Nachricht." };
  }

  console.log('[ServerAction] Email sent successfully')

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

}