import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { calculateMatchPoints } from "@/lib/points";

export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getServerSession(authOptions);
  if (!session || (session.user as any).role !== "ADMIN")
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const stats: Array<{
    playerId: string;
    goals: number;
    assists: number;
    yellowCards: number;
    redCards: number;
    minutesPlayed: number;
    cleanSheet: boolean;
  }> = await req.json();

  const results = [];

  for (const stat of stats) {
    const player = await db.player.findUnique({ where: { id: stat.playerId } });
    if (!player) continue;

    const points = await calculateMatchPoints({
      position: player.position,
      goals: stat.goals,
      assists: stat.assists,
      yellowCards: stat.yellowCards,
      redCards: stat.redCards,
      minutesPlayed: stat.minutesPlayed,
      cleanSheet: stat.cleanSheet,
      penaltySaved: 0,
      penaltyMissed: 0,
      ownGoals: 0,
      isMotm: false,
      extraTimeBonus: 0,
    });

    const record = await db.playerMatchStat.upsert({
      where: { playerId_matchId: { playerId: stat.playerId, matchId: id } },
      update: { ...stat, points },
      create: { ...stat, matchId: id, points },
    });

    // آپدیت امتیاز کل بازیکن
    const totalPoints = await db.playerMatchStat.aggregate({
      where: { playerId: stat.playerId },
      _sum: { points: true },
    });
    await db.player.update({
      where: { id: stat.playerId },
      data: { totalPoints: totalPoints._sum.points ?? 0 },
    });

    results.push(record);
  }

  // آپدیت امتیاز تیم‌های فانتزی
  await recalcTeamPoints();

  return NextResponse.json(results);
}

async function recalcTeamPoints() {
  const teams = await db.team.findMany({ include: { players: { include: { player: true } } } });
  for (const team of teams) {
    let total = 0;
    for (const tp of team.players) {
      const multiplier = tp.isCaptain ? 2 : 1;
      total += tp.player.totalPoints * multiplier;
    }
    await db.team.update({ where: { id: team.id }, data: { totalPoints: total } });
  }
}
