first commit
This commit is contained in:
65
app/api/team/players/route.ts
Normal file
65
app/api/team/players/route.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
|
||||
// اضافه کردن بازیکن به تیم
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const { playerId, isBench } = await req.json();
|
||||
const userId = (session.user as any).id;
|
||||
|
||||
const team = await db.team.findUnique({
|
||||
where: { userId },
|
||||
include: { players: { include: { player: true } } },
|
||||
});
|
||||
|
||||
if (!team) return NextResponse.json({ error: "ابتدا تیم بساز" }, { status: 400 });
|
||||
|
||||
const player = await db.player.findUnique({ where: { id: playerId } });
|
||||
if (!player) return NextResponse.json({ error: "بازیکن پیدا نشد" }, { status: 404 });
|
||||
|
||||
// چک بودجه
|
||||
const spent = team.players.reduce((s, tp) => s + tp.player.price, 0);
|
||||
if (spent + player.price > team.budget)
|
||||
return NextResponse.json({ error: "بودجه کافی نیست" }, { status: 400 });
|
||||
|
||||
// چک تعداد (۱۵ نفر: ۱۱ اصلی + ۴ ذخیره)
|
||||
if (team.players.length >= 15)
|
||||
return NextResponse.json({ error: "تیم پر است (حداکثر ۱۵ بازیکن)" }, { status: 400 });
|
||||
|
||||
// چک تکراری
|
||||
const exists = team.players.find((tp) => tp.playerId === playerId);
|
||||
if (exists) return NextResponse.json({ error: "این بازیکن قبلاً انتخاب شده" }, { status: 400 });
|
||||
|
||||
// چک حداکثر ۳ بازیکن از یک تیم ملی
|
||||
const sameCountry = team.players.filter((tp) => tp.player.countryId === player.countryId).length;
|
||||
if (sameCountry >= 3)
|
||||
return NextResponse.json({ error: "حداکثر ۳ بازیکن از یک تیم ملی" }, { status: 400 });
|
||||
|
||||
const tp = await db.teamPlayer.create({
|
||||
data: { teamId: team.id, playerId, isBench: isBench ?? false },
|
||||
});
|
||||
|
||||
return NextResponse.json(tp, { status: 201 });
|
||||
}
|
||||
|
||||
// حذف بازیکن از تیم
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const { playerId } = await req.json();
|
||||
const userId = (session.user as any).id;
|
||||
|
||||
const team = await db.team.findUnique({ where: { userId } });
|
||||
if (!team) return NextResponse.json({ error: "تیم پیدا نشد" }, { status: 404 });
|
||||
|
||||
await db.teamPlayer.delete({
|
||||
where: { teamId_playerId: { teamId: team.id, playerId } },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
Reference in New Issue
Block a user