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(request: Request) {
  const { searchParams } = new URL(request.url);
  const code = searchParams.get("code") ?? "";
  const state = searchParams.get("state") ?? "";
  const error = searchParams.get("error") ?? "";
  const origin = new URL(request.url).origin;
  const completeUrl = `${origin}/api/square/oauth/complete`;

  // Render an auto-submitting HTML form that POSTs the same params to /complete.
  // This avoids triggering side effects from a GET handler (CSRF-safe pattern).
  const html = `<!doctype html>
<html><head><meta charset="utf-8"><title>Connecting Square…</title></head>
<body>
<p>Completing Square 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" },
  });
}
