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

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 currentRound = await db.round.findUnique({ where: { id } });
  
  if (!currentRound) {
    return NextResponse.json({ error: "Round not found" }, { status: 404 });
  }

  // اگه فعاله، غیرفعالش کن
  if (currentRound.isActive) {
    const round = await db.round.update({ 
      where: { id }, 
      data: { isActive: false } 
    });
    return NextResponse.json(round);
  }

  // اگه غیرفعاله، همه رو غیرفعال کن و این رو فعال کن
  await db.round.updateMany({ data: { isActive: false } });
  const round = await db.round.update({ 
    where: { id }, 
    data: { isActive: true } 
  });
  return NextResponse.json(round);
}
