interface Env {
  POSTMARK_SERVER_TOKEN: string;
}

const VALID_SIZES = ["1–50", "51–200", "201–1,000", "1,000+"];

const rateMap = new Map<string, { count: number; resetAt: number }>();

export const onRequestPost: PagesFunction<Env> = async (context) => {
  try {
    let body: Record<string, unknown>;
    try {
      body = await context.request.json();
    } catch {
      return Response.json({ error: "Invalid request" }, { status: 400 });
    }

    // Honeypot check
    if (body.website && typeof body.website === "string" && body.website.trim() !== "") {
      return Response.json({ success: true });
    }

    // Validate required fields
    const company = typeof body.company === "string" ? body.company.trim() : "";
    const name = typeof body.name === "string" ? body.name.trim() : "";
    const email = typeof body.email === "string" ? body.email.trim() : "";
    const companySize = typeof body.company_size === "string" ? body.company_size : "";

    if (!company || !name || !email || !email.includes("@") || !VALID_SIZES.includes(companySize)) {
      return Response.json({ error: "Missing or invalid required fields" }, { status: 400 });
    }

    // Rate limit (best-effort, in-memory)
    const ip = context.request.headers.get("CF-Connecting-IP") || "unknown";
    const now = Date.now();
    const entry = rateMap.get(ip);

    if (entry) {
      if (now > entry.resetAt) {
        rateMap.set(ip, { count: 1, resetAt: now + 3600000 });
      } else if (entry.count >= 3) {
        return Response.json({ error: "Too many requests. Please try again later." }, { status: 429 });
      } else {
        entry.count++;
      }
    } else {
      rateMap.set(ip, { count: 1, resetAt: now + 3600000 });
    }

    // Build template model
    const clouds = Array.isArray(body.clouds) ? body.clouds.filter((c): c is string => typeof c === "string").join(", ") : "";
    const frameworks = typeof body.frameworks === "string" ? body.frameworks.trim() : "";
    const engagements = typeof body.engagements === "string" ? body.engagements.trim() : "";
    const requirements = typeof body.requirements === "string" ? body.requirements.trim() : "";

    // Send via Postmark
    try {
      const res = await fetch("https://api.postmarkapp.com/email/withTemplate", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-Postmark-Server-Token": context.env.POSTMARK_SERVER_TOKEN,
        },
        body: JSON.stringify({
          From: "noreply@complyform.dev",
          To: "sales@complyform.dev",
          TemplateAlias: "enterprise-quote-request",
          TemplateModel: {
            company,
            name,
            email,
            company_size: companySize,
            clouds: clouds || "None selected",
            frameworks: frameworks || "Not specified",
            engagements: engagements || "Not specified",
            requirements: requirements || "Not specified",
          },
        }),
      });

      if (!res.ok) {
        console.error("Postmark error:", res.status);
      }
    } catch (err) {
      console.error("Postmark request failed:", err);
    }

    return Response.json({ success: true });
  } catch (err) {
    console.error("Unhandled error:", err);
    return Response.json({ error: "Internal error" }, { status: 500 });
  }
};
