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

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

/** Proxy: submit GSTIN + captcha answer → taxpayer data */
export async function POST(req: NextRequest) {
  const session = await auth();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json();
  if (!body.sessionId || !body.gstin || !body.captcha) {
    return NextResponse.json({ error: "sessionId, gstin and captcha are required" }, { status: 400 });
  }

  try {
    const res = await fetch(`${GST_SERVICE}/search`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
      cache: "no-store",
    });
    const data = await res.json();
    return NextResponse.json(data, { status: res.ok ? 200 : res.status });
  } catch (e) {
    return NextResponse.json({ error: `GST service unavailable: ${String(e)}` }, { status: 502 });
  }
}
