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

const validTiers = new Set(["GOLD", "SILVER", "BRONZE"]);

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session || (session.user as any).role !== "ADMIN") {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const { cardTier } = await req.json();

  if (!validTiers.has(cardTier)) {
    return NextResponse.json({ error: "Invalid card tier" }, { status: 400 });
  }

  const updated = await db.player.update({
    where: { id },
    data: {
      cardTier,
      isGoldenCardEligible: cardTier === "GOLD",
    },
  });

  return NextResponse.json(updated);
}
