import { Router, Request } from 'express';
import { createLogger } from '../utils/logger';
import { sendContactFormEmail } from '../utils/email';
import { config } from '../config';

const router = Router();
const logger = createLogger('ContactRoutes');

/** Verify a Cloudflare Turnstile token server-side. Returns true on success. */
async function verifyTurnstileToken(token: string, remoteIp: string): Promise<boolean> {
  if (!config.turnstile.secretKey) {
    logger.warn('TURNSTILE_SECRET not configured — skipping Turnstile verification');
    return true;
  }

  if (typeof token !== 'string' || token.length === 0 || token.length > 2048) {
    return false;
  }

  try {
    const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      signal: AbortSignal.timeout(10_000),
      body: new URLSearchParams({
        secret: config.turnstile.secretKey,
        response: token,
        remoteip: remoteIp,
      }),
    });

    if (!res.ok) {
      logger.warn('Turnstile siteverify returned non-OK status', { status: res.status });
      return false;
    }

    const result = await res.json() as { success: boolean; action?: string };
    if (!result.success) {
      logger.warn('Turnstile verification failed', { result });
      return false;
    }

    if (result.action && result.action !== 'contact-form') {
      logger.warn('Turnstile action mismatch', { action: result.action });
      return false;
    }

    return true;
  } catch (err) {
    logger.error('Turnstile siteverify request failed', {
      error: err instanceof Error ? err.message : String(err),
    });
    return false;
  }
}

/**
 * POST /contact
 * Submit a contact form — sends an email to info@cahootravel.com (public, no auth).
 */
router.post('/', async (req: Request, res) => {
  try {
    const {
      firstName, lastName, email, phone,
      company, country, companySize, potentialUsers,
      helpWith, product, message, turnstileToken,
    } = req.body;

    if (!firstName || !lastName || !email || !message) {
      res.status(400).json({ error: 'firstName, lastName, email, and message are required' });
      return;
    }

    if (typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      res.status(400).json({ error: 'Invalid email address' });
      return;
    }

    if (typeof message !== 'string' || message.trim().length < 5) {
      res.status(400).json({ error: 'Message must be at least 5 characters' });
      return;
    }

    if (message.length > 5000) {
      res.status(400).json({ error: 'Message must be 5000 characters or fewer' });
      return;
    }

    const remoteIp = (req.headers['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim()
      ?? req.socket.remoteAddress
      ?? '';

    const turnstileOk = await verifyTurnstileToken(String(turnstileToken ?? ''), remoteIp);
    if (!turnstileOk) {
      res.status(403).json({ error: 'Verification failed. Please try again.' });
      return;
    }

    await sendContactFormEmail({
      firstName: String(firstName).trim(),
      lastName: String(lastName).trim(),
      email: String(email).trim(),
      phone: phone ? String(phone).trim() : undefined,
      company: company ? String(company).trim() : undefined,
      country: country ? String(country).trim() : undefined,
      companySize: companySize ? String(companySize).trim() : undefined,
      potentialUsers: potentialUsers ? String(potentialUsers).trim() : undefined,
      helpWith: helpWith ? String(helpWith).trim() : undefined,
      product: product ? String(product).trim() : undefined,
      message: String(message).trim(),
    });

    logger.info('Contact form submitted', { email: String(email).trim() });
    res.status(200).json({ message: 'Your message has been sent. We\'ll be in touch soon.' });
  } catch (error) {
    logger.error('Failed to send contact form email', {
      error: error instanceof Error ? error.message : String(error),
    });
    res.status(500).json({ error: 'Failed to send your message. Please try again.' });
  }
});

export default router;
