'use server'

import { z } from 'zod'
import { sendContactEmail } from './contact-mailer'

const ContactSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Valid email address required'),
  phone: z.string().min(7, 'Phone number is required'),
  message: z.string().min(10, 'Message must be at least 10 characters'),
  website: z.string(), // honeypot — must remain empty
})

export type ContactState = {
  status: 'idle' | 'success' | 'error'
  message?: string
}

export async function submitContact(
  _prev: ContactState,
  formData: FormData,
): Promise<ContactState> {
  const raw = {
    name: formData.get('name'),
    email: formData.get('email'),
    phone: formData.get('phone'),
    message: formData.get('message'),
    website: formData.get('website') ?? '',
  }

  const parsed = ContactSchema.safeParse(raw)
  if (!parsed.success) {
    return { status: 'error', message: 'Please fill in all required fields correctly.' }
  }

  // Honeypot check — if filled, silently succeed (don't reveal rejection to bots)
  if (parsed.data.website !== '') {
    return { status: 'success' }
  }

  try {
    await sendContactEmail(parsed.data)
    return { status: 'success' }
  } catch (err) {
    console.error('Contact form email error:', err)
    return { status: 'error', message: 'Something went wrong. Please try again or call directly.' }
  }
}
