import type { Context } from "@wrnexus/core";
import { captchaGuard } from "@wrnexus/captcha/server";
import { parseBody } from "@wrnexus/validation";
import contactSchema from "../schemas/contact.ts";
import { captchaEngine } from "../lib/captcha.ts";

const protectContact = captchaGuard({
  action: "contact-submit",
  engine: captchaEngine,
  responseField: "wrn-captcha-response",
  bindHostname: true,
  bindSession: true,
});

interface ContactInput {
  name: string;
  email: string;
  topic: "general" | "security" | "billing" | "integration";
  message: string;
  consent: boolean;
}

export async function POST(ctx: Context): Promise<Response> {
  const validation = await parseBody<ContactInput>(contactSchema, ctx.req.clone());
  if (!validation.ok) return validation.response;

  return protectContact(ctx, async () =>
    Response.json({
      ok: true,
      message: "Validated CAPTCHA form accepted.",
      submission: {
        name: validation.value.name,
        email: validation.value.email,
        topic: validation.value.topic,
        messageLength: validation.value.message.length,
      },
    }),
  );
}
