// API route: POST /api/invite. Validates the body with the SAME schema the
// modal's invite form uses in the browser, so a request that bypasses the
// client (curl, a replayed fetch, a stale page) is held to identical rules.
//
// There is no mail provider wired up in the example, so a successful parse
// just echoes the invite back. The point being demonstrated is the shared
// schema and the client/server round trip, not delivery.
import { verifyCsrf, type Context } from "@wrnexus/core";
import { parseBody } from "@wrnexus/validation";
import invite from "../schemas/invite.ts";

export async function POST(ctx: Context): Promise<Response> {
  if (!verifyCsrf(ctx)) return new Response("Invalid CSRF token", { status: 403 });

  const result = await parseBody(invite, ctx.req);
  if (!result.ok) return result.response; // 400 { ok:false, errors } — rendered per field

  const { email, message } = result.value as { email: string; message?: string };

  return Response.json({
    ok: true,
    email,
    message: message ?? "",
    sentAt: new Date().toISOString(),
  });
}
