/**
 * POST /api/demo-request
 *
 * Receives demo request form submissions from the website
 * and emails the details to hello@stylobridge.ai.
 */

import type { Context } from "hono";
import type { Env } from "../env.d";
import { sendEmail } from "../lib/send-email";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

interface DemoRequest {
  first_name: string;
  work_email: string;
  company: string;
  team_size?: string;
  use_case?: string;
}

export async function handleDemoRequest(c: Context): Promise<Response> {
  const env = c.env as Env;

  let body: DemoRequest;
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: "Invalid JSON body" }, 400);
  }

  if (!body.first_name?.trim()) {
    return c.json({ error: "first_name is required" }, 400);
  }
  if (!body.work_email?.trim()) {
    return c.json({ error: "work_email is required" }, 400);
  }
  if (!EMAIL_RE.test(body.work_email.trim())) {
    return c.json({ error: "Invalid email address" }, 400);
  }
  if (!body.company?.trim()) {
    return c.json({ error: "company is required" }, 400);
  }

  const html = `
    <h2>New Demo Request</h2>
    <table style="border-collapse:collapse;font-family:sans-serif;font-size:14px;">
      <tr><td style="padding:6px 12px;font-weight:bold;">Name</td><td style="padding:6px 12px;">${escapeHtml(body.first_name.trim())}</td></tr>
      <tr><td style="padding:6px 12px;font-weight:bold;">Email</td><td style="padding:6px 12px;">${escapeHtml(body.work_email.trim())}</td></tr>
      <tr><td style="padding:6px 12px;font-weight:bold;">Company</td><td style="padding:6px 12px;">${escapeHtml(body.company.trim())}</td></tr>
      <tr><td style="padding:6px 12px;font-weight:bold;">Team Size</td><td style="padding:6px 12px;">${escapeHtml(body.team_size || "Not specified")}</td></tr>
      <tr><td style="padding:6px 12px;font-weight:bold;">Use Case</td><td style="padding:6px 12px;">${escapeHtml(body.use_case || "Not specified")}</td></tr>
    </table>
  `;

  if (!env.RESEND_API_KEY) {
    // Log to console if no email configured
    console.log("Demo request (no RESEND_API_KEY):", JSON.stringify(body));
    return c.json({ success: true, note: "Logged but not emailed (no RESEND_API_KEY)" });
  }

  try {
    await sendEmail(
      {
        to: "hello@stylobridge.ai",
        subject: `Demo Request: ${body.first_name.trim()} at ${body.company.trim()}`,
        html,
      },
      env.RESEND_API_KEY
    );
  } catch (err) {
    console.error("Failed to send demo request email:", err);
    return c.json({ error: "Failed to send notification" }, 500);
  }

  return c.json({ success: true });
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}
