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, goldenCard: 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
    .filter((item) => !item.goldenCardId)
    .reduce((sum, item) => sum + item.player.price, 0);
  if (spent + player.price > team.budget) {
    return NextResponse.json({ error: "بودجه کافی نیست" }, { status: 400 });
  }

  if (team.players.length >= 15) {
    return NextResponse.json({ error: "تیم پر است (حداکثر 15 بازیکن)" }, { status: 400 });
  }

  const exists = team.players.find((item) => item.playerId === playerId);
  if (exists) {
    return NextResponse.json({ error: "این بازیکن قبلاً انتخاب شده" }, { status: 400 });
  }

  const sameCountry = team.players.filter((item) => item.player.countryId === player.countryId).length;
  if (sameCountry >= 3) {
    return NextResponse.json({ error: "حداکثر 3 بازیکن از یک تیم ملی" }, { status: 400 });
  }

  const teamPlayer = await db.teamPlayer.create({
    data: { teamId: team.id, playerId, isBench: isBench ?? false },
  });

  return NextResponse.json(teamPlayer, { 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 },
    include: { players: true },
  });
  if (!team) return NextResponse.json({ error: "تیم پیدا نشد" }, { status: 404 });

  const teamPlayer = team.players.find((item) => item.playerId === playerId);
  if (!teamPlayer) return NextResponse.json({ error: "بازیکن در تیم نیست" }, { status: 404 });

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

    if (teamPlayer.goldenCardId) {
      await tx.goldenCard.update({
        where: { id: teamPlayer.goldenCardId },
        data: { state: "IN_INVENTORY" },
      });
    }
  });

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