import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { verifyPayment } from "@/lib/zarinpal";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const authority = searchParams.get("Authority");
  const status = searchParams.get("Status");

  if (!authority) return NextResponse.redirect(new URL("/shop?status=error", req.url));

  const payment = await db.payment.findUnique({
    where: { authority },
    include: { package: true, user: true },
  });

  if (!payment) return NextResponse.redirect(new URL("/shop?status=error", req.url));

  if (status !== "OK") {
    await db.payment.update({ where: { id: payment.id }, data: { status: "FAILED" } });
    return NextResponse.redirect(new URL("/shop?status=cancelled", req.url));
  }

  const result = await verifyPayment(authority, payment.amount);

  if (!result.success) {
    await db.payment.update({ where: { id: payment.id }, data: { status: "FAILED" } });
    return NextResponse.redirect(new URL("/shop?status=failed", req.url));
  }

  // پرداخت موفق - آپدیت بودجه تیم
  await db.payment.update({
    where: { id: payment.id },
    data: { status: "SUCCESS", refId: result.refId },
  });

  await db.team.updateMany({
    where: { userId: payment.userId },
    data: { budget: { increment: payment.package.budgetBonus } },
  });

  return NextResponse.redirect(new URL(`/shop?status=success&refId=${result.refId}`, req.url));
}
