import { auth } from "@/auth";
import { NextRequest, NextResponse } from "next/server";

const GST_SERVICE = process.env.GST_SERVICE_URL ?? "http://localhost:3003";

/**
 * GET /api/gst/captcha
 * Create a new GST session and return the first captcha image.
 * Response: { sessionId, captchaId, captchaBase64 }
 *
 * GET /api/gst/captcha?refresh=<sessionId>
 * Refresh the captcha for an existing session (no page reload).
 * Response: { captchaId, captchaBase64, totalCaptchas }
 */
export async function GET(req: NextRequest) {
  const session = await auth();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const refreshId = req.nextUrl.searchParams.get("refresh");

  try {
    const upstream = refreshId
      ? await fetch(`${GST_SERVICE}/captcha/${encodeURIComponent(refreshId)}`, { cache: "no-store" })
      : await fetch(`${GST_SERVICE}/captcha`, { cache: "no-store" });

    const data = await upstream.json();
    return NextResponse.json(data, { status: upstream.ok ? 200 : upstream.status });
  } catch (e) {
    return NextResponse.json(
      { error: `GST service unavailable: ${String(e)}` },
      { status: 502 }
    );
  }
}
