import { NextResponse } from "next/server";

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

export async function GET(req: Request) {
  const url = new URL(req.url);
  const code = url.searchParams.get("code") ?? "";
  const state = url.searchParams.get("state") ?? "";
  const error = url.searchParams.get("error") ?? "";
  const origin = url.origin;
  const completeUrl = `${origin}/api/stripe/oauth/complete`;

  const html = `<!doctype html>
<html><head><meta charset="utf-8"><title>Connecting Stripe…</title></head>
<body>
<p>Completing Stripe connection…</p>
<form id="f" method="POST" action="${escapeAttr(completeUrl)}">
  <input type="hidden" name="code" value="${escapeAttr(code)}" />
  <input type="hidden" name="state" value="${escapeAttr(state)}" />
  <input type="hidden" name="error" value="${escapeAttr(error)}" />
  <noscript><button type="submit">Continue</button></noscript>
</form>
<script>document.getElementById('f').submit();</script>
</body></html>`;
  return new NextResponse(html, {
    status: 200,
    headers: { "content-type": "text/html; charset=utf-8" },
  });
}
