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

// POST /api/golden-cards/[id]/reveal
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const userId = (session.user as any).id;
  const { id } = await params;

  const card = await db.goldenCard.findUnique({ where: { id } });
  if (!card) return NextResponse.json({ error: "Card not found" }, { status: 404 });
  if (card.userId !== userId) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  if (card.status === "OPENED") return NextResponse.json({ error: "کارت قبلاً باز شده" }, { status: 400 });

  const updated = await db.goldenCard.update({
    where: { id },
    data: { status: "OPENED", openedAt: new Date() },
    include: { player: { include: { country: true } } },
  });

  return NextResponse.json(updated);
}
