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

export async function GET() {
  const rounds = await db.round.findMany({ orderBy: { number: "asc" } });
  return NextResponse.json(rounds);
}

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

  const { number, name, deadline } = await req.json();

  const existing = await db.round.findUnique({ where: { number } });
  if (existing) return NextResponse.json({ error: "این شماره دور قبلاً ثبت شده" }, { status: 400 });

  const round = await db.round.create({
    data: { number, name, deadline: new Date(deadline) },
  });
  return NextResponse.json(round, { status: 201 });
}

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 { id, number, name, deadline } = await req.json();

  const round = await db.round.update({
    where: { id },
    data: { number, name, deadline: new Date(deadline) },
  });
  return NextResponse.json(round);
}

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

  const { id } = await req.json();

  // چک کنیم که بازی نداشته باشه
  const matchCount = await db.match.count({ where: { roundId: id } });
  if (matchCount > 0) {
    return NextResponse.json({ error: "این دور دارای بازی است و قابل حذف نیست" }, { status: 400 });
  }

  await db.round.delete({ where: { id } });
  return NextResponse.json({ success: true });
}
