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

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

  const { formation } = await req.json();
  if (!FORMATIONS[formation]) return NextResponse.json({ error: "ترکیب نامعتبر" }, { status: 400 });

  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 issues = getFormationChangeIssues(playerList, team.formation, formation);

  if (issues.length > 0) {
    return NextResponse.json({ error: issues.join(" | "), issues }, { status: 400 });
  }

  const updated = await db.team.update({ where: { id: team.id }, data: { formation } });
  return NextResponse.json(updated);
}
