import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAdmin, unauthorized } from "@/lib/admin-api";

type Ctx = { params: Promise<{ id: string }> };

export async function PATCH(req: Request, ctx: Ctx) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  const { id } = await ctx.params;
  const body = await req.json();
  const m = await prisma.match.update({
    where: { id },
    data: {
      ...(body.opponent != null && { opponent: body.opponent }),
      ...(body.opponentLogoUrl !== undefined && { opponentLogoUrl: body.opponentLogoUrl || null }),
      ...(body.competition !== undefined && { competition: body.competition }),
      ...(body.venue !== undefined && { venue: body.venue }),
      ...(body.matchAt && { matchAt: new Date(body.matchAt) }),
      ...(body.isHome !== undefined && { isHome: Boolean(body.isHome) }),
      ...(body.result !== undefined && { result: body.result }),
    },
  });
  return NextResponse.json(m);
}

export async function DELETE(_req: Request, ctx: Ctx) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  await prisma.match.delete({ where: { id: (await ctx.params).id } });
  return NextResponse.json({ ok: true });
}
