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

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

  const rules: Array<{ position: string; eventType: string; points: number }> = await req.json();

  for (const rule of rules) {
    await db.scoringRule.upsert({
      where: { position_eventType: { position: rule.position as any, eventType: rule.eventType as any } },
      update: { points: rule.points, updatedBy: (session.user as any).id },
      create: { position: rule.position as any, eventType: rule.eventType as any, points: rule.points, updatedBy: (session.user as any).id },
    });
  }

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