import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { requestPayment } from "@/lib/zarinpal";

export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { packageId } = await req.json();
  const userId = (session.user as any).id;

  const pkg = await db.package.findUnique({ where: { id: packageId } });
  if (!pkg || !pkg.isActive) return NextResponse.json({ error: "پکیج پیدا نشد" }, { status: 404 });

  const callbackUrl = `${process.env.NEXTAUTH_URL}/api/payment/verify`;

  const result = await requestPayment(pkg.price, `خرید ${pkg.name} - فانتزی جام جهانی`, callbackUrl);

  if (!result.success) return NextResponse.json({ error: result.error }, { status: 400 });

  // ذخیره پرداخت در دیتابیس
  await db.payment.create({
    data: {
      userId,
      packageId,
      amount: pkg.price,
      authority: result.authority,
      status: "PENDING",
    },
  });

  return NextResponse.json({ paymentUrl: result.paymentUrl });
}
