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

export async function POST(_: Request, { 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 },
    include: { player: true, teamPlayer: true },
  });

  if (!card) return NextResponse.json({ error: "کارت ویژه پیدا نشد" }, { status: 404 });
  if (card.userId !== userId) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  if (card.status !== "OPENED") return NextResponse.json({ error: "ابتدا کارت را باز کنید" }, { status: 400 });
  if (card.state === "SOLD") return NextResponse.json({ error: "این کارت قبلاً فروخته شده" }, { status: 400 });

  const team = await db.team.findUnique({ where: { userId } });
  if (!team) return NextResponse.json({ error: "تیم پیدا نشد" }, { status: 404 });

  const addedBudget = getSpecialCardSalePrice(card.player.price);

  await db.$transaction(async (tx) => {
    if (card.teamPlayer) {
      await tx.teamPlayer.delete({
        where: { teamId_playerId: { teamId: card.teamPlayer.teamId, playerId: card.teamPlayer.playerId } },
      });
    }

    await tx.goldenCard.update({
      where: { id },
      data: { state: "SOLD" },
    });

    await tx.team.update({
      where: { id: team.id },
      data: { budget: { increment: addedBudget } },
    });
  });

  return NextResponse.json({
    success: true,
    addedBudget,
    cardId: id,
  });
}
