import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getApiUser } from "@/lib/apiAuth";
export async function PUT(req: NextRequest) {
  const apiUser = await getApiUser(req);
  if (!apiUser) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { playerId, type } = await req.json();
  const team = await db.team.findUnique({ where: { userId: apiUser.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 });
}
