import { Request, Response } from 'express';
import { sendContactViaBrevo, isBrevoContactConfigured, ContactEmailPayload } from '../lib/email';

const ALLOWED_SERVICES = new Set([
  'coaching',
  'therapy',
  'stress',
  'parenting',
  'training',
  'nutrition',
  'mental-health',
  'other',
]);

const MAX = { name: 120, email: 254, phone: 40, message: 8000 };

function trimStr(v: unknown, max: number): string | null {
  if (typeof v !== 'string') return null;
  const s = v.trim();
  if (!s) return null;
  return s.length > max ? s.slice(0, max) : s;
}

export async function postContact(
  req: Request<unknown, unknown, Partial<ContactEmailPayload>>,
  res: Response<{ ok: true } | { error: string }>
): Promise<void> {
  try {
    const firstName = trimStr(req.body.firstName, MAX.name);
    const lastName = trimStr(req.body.lastName, MAX.name);
    const email = trimStr(req.body.email, MAX.email);
    const phone = trimStr(req.body.phone, MAX.phone) ?? '';
    const service = typeof req.body.service === 'string' ? req.body.service.trim() : '';
    const message = trimStr(req.body.message, MAX.message);

    if (!firstName || !lastName || !email || !message) {
      res.status(400).json({ error: 'Please fill in all required fields.' });
      return;
    }

    if (!ALLOWED_SERVICES.has(service)) {
      res.status(400).json({ error: 'Please select a valid service.' });
      return;
    }

    const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    if (!emailOk) {
      res.status(400).json({ error: 'Please enter a valid email address.' });
      return;
    }

    await sendContactViaBrevo({
      firstName,
      lastName,
      email,
      phone: phone || undefined,
      service,
      message,
    });

    res.json({ ok: true });
  } catch (err) {
    console.error('Contact form error:', err);
    const configured = isBrevoContactConfigured();
    if (!configured) {
      res.status(503).json({ error: 'Contact form is not configured yet. Please email us directly.' });
      return;
    }
    res.status(500).json({ error: 'Something went wrong sending your message. Please try again or email us directly.' });
  }
}
