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(_: 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 events = await db.matchEvent.findMany({
    where: { matchId: id },
    include: { player: true },
  });

  // گروه‌بندی رویدادها بر اساس بازیکن
  const playerEvents: Record<string, { player: any; events: any[] }> = {};
  for (const ev of events) {
    if (!playerEvents[ev.playerId]) playerEvents[ev.playerId] = { player: ev.player, events: [] };
    playerEvents[ev.playerId].events.push(ev);
  }

  const results = [];

  for (const [playerId, { player, events: evs }] of Object.entries(playerEvents)) {
    const goals = evs.filter((e) => e.type === "GOAL").length;
    const assists = evs.filter((e) => e.type === "ASSIST").length;
    const yellowCards = evs.filter((e) => e.type === "YELLOW_CARD" || e.type === "SECOND_YELLOW").length;
    const redCards = evs.filter((e) => e.type === "RED_CARD" || e.type === "SECOND_YELLOW").length;
    const cleanSheet = evs.some((e) => e.type === "CLEAN_SHEET");
    const penaltySaved = evs.filter((e) => e.type === "PENALTY_SAVED").length;
    const penaltyMissed = evs.filter((e) => e.type === "PENALTY_MISSED").length;
    const ownGoals = evs.filter((e) => e.type === "OWN_GOAL").length;
    const isMotm = evs.some((e) => e.type === "MOTM");
    const extraTimeBonus = evs.filter((e) => e.type === "EXTRA_TIME_BONUS").length;

    // دقیقه بازی: اگه تعویض شده کمتر از ۹۰، وگرنه ۹۰
    const subOut = evs.find((e) => e.type === "SUBSTITUTION_OUT");
    const subIn = evs.find((e) => e.type === "SUBSTITUTION_IN");
    const injury = evs.find((e) => e.type === "INJURY_NO_SUB");
    let minutesPlayed = 90;
    if (subOut?.minute) minutesPlayed = subOut.minute;
    else if (injury?.minute) minutesPlayed = injury.minute;
    if (subIn?.minute) minutesPlayed = 90 - subIn.minute;

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

    const stat = await db.playerMatchStat.upsert({
      where: { playerId_matchId: { playerId, matchId: id } },
      update: { goals, assists, yellowCards, redCards, minutesPlayed, cleanSheet, penaltySaved, penaltyMissed, ownGoals, isMotm, extraTimeBonus, points },
      create: { playerId, matchId: id, goals, assists, yellowCards, redCards, minutesPlayed, cleanSheet, penaltySaved, penaltyMissed, ownGoals, isMotm, extraTimeBonus, points },
    });

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

    results.push(stat);
  }

  // آپدیت امتیاز تیم‌های فانتزی
  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 mult = tp.isCaptain ? 2 : tp.isViceCaptain ? 1.5 : 1;
      total += tp.player.totalPoints * mult;
    }
    await db.team.update({ where: { id: team.id }, data: { totalPoints: Math.round(total) } });
  }

  return NextResponse.json({ calculated: results.length });
}
