import { retrieveOrder } from "@/lib/areeba";

export async function POST(req: Request) {
  const body = await req.json();
  const { orderId, resultIndicator, successIndicator } = body;

  if (!orderId)
    return new Response(JSON.stringify({ error: "Missing order id." }), {
      status: 400,
    });

  try {
    const order = await retrieveOrder(orderId);

    // The gateway appends resultIndicator to the return URL after payment;
    // it must match the successIndicator issued when the session was created.
    const indicatorMatches =
      !successIndicator || resultIndicator === successIndicator;

    return new Response(
      JSON.stringify({
        success: order.paid && indicatorMatches,
        status: order.status,
        amount: order.amount,
        currency: order.currency,
      }),
    );
  } catch (err) {
    console.log("[AREEBA_PAYMENT_VERIFY]: ", err);

    return new Response(JSON.stringify({ error: "Internal Server Error" }), {
      status: 500,
    });
  }
}
