import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const HUBSPOT_SUBMIT_BASE = "https://api.hsforms.com/submissions/v3/integration/submit";
const TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
const CONSENT_TEXT = "J'accepte que Covalba traite mes données pour me recontacter.";

const fieldSchema = z.object({
  objectTypeId: z.string().optional(),
  name: z.string().min(1).max(120),
  value: z.string().max(5000),
});

const submitSchema = z.object({
  portalId: z.string().min(1).max(64),
  formGuid: z.string().min(1).max(128),
  captchaToken: z.string().optional(),
  fields: z.array(fieldSchema).min(1).max(50),
  context: z
    .object({
      pageUri: z.string().url().optional(),
      pageName: z.string().max(300).optional(),
      hutk: z.string().max(200).optional(),
    })
    .optional(),
});

type SubmitPayload = z.infer<typeof submitSchema>;

function clientIp(request: NextRequest): string | undefined {
  const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
  return forwarded || request.headers.get("x-real-ip") || undefined;
}

async function verifyTurnstile(token: string | undefined, ip?: string): Promise<boolean> {
  const secret = process.env.TURNSTILE_SECRET_KEY;

  if (!secret) {
    return process.env.NODE_ENV !== "production";
  }

  if (!token) return false;

  const body = new FormData();
  body.set("secret", secret);
  body.set("response", token);
  if (ip) body.set("remoteip", ip);

  const res = await fetch(TURNSTILE_VERIFY_URL, { method: "POST", body, cache: "no-store" });
  if (!res.ok) return false;

  const json = (await res.json().catch(() => null)) as { success?: boolean } | null;
  return Boolean(json?.success);
}

async function submitToHubspot(payload: SubmitPayload) {
  return fetch(`${HUBSPOT_SUBMIT_BASE}/${payload.portalId}/${payload.formGuid}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      fields: payload.fields,
      context: payload.context ?? {},
      legalConsentOptions: {
        consent: { consentToProcess: true, text: CONSENT_TEXT },
      },
    }),
    cache: "no-store",
  });
}

export async function POST(request: NextRequest) {
  let payload: SubmitPayload;
  try {
    payload = submitSchema.parse(await request.json());
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid payload" }, { status: 400 });
  }

  const captchaOk = await verifyTurnstile(payload.captchaToken, clientIp(request));
  if (!captchaOk) {
    return NextResponse.json({ ok: false, error: "Captcha failed" }, { status: 403 });
  }

  const res = await submitToHubspot(payload);
  if (!res.ok) {
    const detail = await res.text().catch(() => "");
    return NextResponse.json(
      { ok: false, error: "HubSpot submit failed", detail: detail.slice(0, 500) },
      { status: res.status },
    );
  }

  return NextResponse.json({ ok: true });
}
