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

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

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

  if (type === "captain") {
    await db.teamPlayer.updateMany({ where: { teamId: team.id }, data: { isCaptain: false } });
    await db.teamPlayer.update({ where: { teamId_playerId: { teamId: team.id, playerId } }, data: { isCaptain: true } });
  } else {
    await db.teamPlayer.updateMany({ where: { teamId: team.id }, data: { isViceCaptain: false } });
    await db.teamPlayer.update({ where: { teamId_playerId: { teamId: team.id, playerId } }, data: { isViceCaptain: true } });
  }

  return NextResponse.json({ success: true });
}
