// import { NextResponse } from "next/server";
// export async function POST(req: Request) {
//   try {
//     const formData = await req.formData();
//     const data = formData.get("data");
//     const mandateReqDoc = formData.get("mandateReqDoc");
//     const mndtType = formData.get("mndtType");
//     // const { searchParams } = new URL(req.url);
//     // const data = searchParams.get("data");
//     // const mandateReqDoc = searchParams.get("mandateReqDoc");
//     // const mndtType = searchParams.get("mndtType");

//     console.log("Received from SoftTech:", { data, mandateReqDoc, mndtType });
//     if (!data) {
//       return NextResponse.json({ error: "Missing data" }, { status: 400 });
//     }
//     const encodedData = String(data);
//     const forwardedHost =
//       req.headers.get("x-forwarded-host") || "netbankingtest.kccb.in";
//     const forwardedProto = req.headers.get("x-forwarded-proto") || "https";

//     const redirectUrl = `${forwardedProto}://${forwardedHost}/eMandate/login/page?data=${encodedData}`;

//     console.log("Redirecting to:", redirectUrl);
//     return NextResponse.redirect(redirectUrl);
    
//   } catch (error) {
//     console.error("Error handling POST:", error);
//     return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
//   }
// }

import { NextResponse } from "next/server";

export async function POST(req: Request) {
  try {
    const formData = await req.formData();
    const data = formData.get("data");
    const mandateReqDoc = formData.get("mandateReqDoc");
    const mndtType = formData.get("mndtType");

    console.log("Received from SoftTech:", { data, mandateReqDoc, mndtType });
    const forwardedHost = req.headers.get("x-forwarded-host") || req.headers.get("host");
    const forwardedProto = req.headers.get("x-forwarded-proto") || "https";
    const encodedData = String(data);

    const redirectUrl = `${forwardedProto}://${forwardedHost}/eMandate/login/page?data=${encodedData}`;

    const response = NextResponse.redirect(redirectUrl, 303); //  use 303 instead of 302

    response.headers.set("Access-Control-Allow-Origin", "*");
    response.headers.set("Access-Control-Allow-Methods", "POST, OPTIONS");
    response.headers.set("Access-Control-Allow-Headers", "Content-Type, Origin");

    return response;
  } catch (error) {
    console.error("Error handling POST:", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}

export async function OPTIONS() {
  const res = new NextResponse(null, { status: 204 });
  res.headers.set("Access-Control-Allow-Origin", "*");
  res.headers.set("Access-Control-Allow-Methods", "POST, OPTIONS");
  res.headers.set("Access-Control-Allow-Headers", "Content-Type, Origin");
  return res;
}
