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

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

  const team = await db.team.findUnique({
    where: { userId: (session.user as any).id },
    include: { players: { include: { player: true } } },
  });

  if (!team) return NextResponse.json({ error: "تیم پیدا نشد" }, { status: 404 });

  const playerList = team.players.map((tp) => ({
    position: tp.player.position,
    isBench: tp.isBench,
  }));

  const { valid, errors } = validateTeamComposition(playerList, team.formation);
  if (!valid) return NextResponse.json({ error: errors.join(" | ") }, { status: 400 });

  // مستقیم ACTIVE میشه - نیازی به تایید ادمین نیست
  const updated = await db.team.update({
    where: { id: team.id },
    data: { status: "ACTIVE" },
  });

  return NextResponse.json(updated);
}
