'use server';

import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { sendContactMessageNotification } from '@/lib/mail';
import { verifyTurnstileToken } from '@/lib/turnstile';
import { getClientIp } from '@/lib/rateLimit';

export async function sendContactMessage(formData: FormData) {
  const name = String(formData.get('name') ?? '').trim();
  const email = String(formData.get('email') ?? '').trim();
  const message = String(formData.get('message') ?? '').trim();

  if (!name || !email || !message) {
    redirect('/contact?error=missing');
  }

  const ip = getClientIp(headers());
  const turnstileToken = String(formData.get('cf-turnstile-response') ?? '');
  const { success } = await verifyTurnstileToken(turnstileToken, ip);
  if (!success) {
    redirect('/contact?error=captcha');
  }

  await sendContactMessageNotification({ name, email, message });

  redirect('/contact?sent=1');
}
