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

const schema = z.object({
  opponent: z.string().min(1).optional(),
  opponentLogoUrl: z.string().optional(),
  competition: z.string().optional(),
  venue: z.string().optional(),
  matchAt: z.string().optional(),
  isHome: z.boolean().optional(),
  result: z.string().optional(),
  sortOrder: z.number().int().optional(),
});

export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  const { id } = await params;
  const body = schema.parse(await req.json());
  const item = await prisma.baseMatch.update({
    where: { id },
    data: {
      opponent: body.opponent,
      opponentLogoUrl: body.opponentLogoUrl === undefined ? undefined : body.opponentLogoUrl.trim() || null,
      competition: body.competition === undefined ? undefined : body.competition.trim() || null,
      venue: body.venue === undefined ? undefined : body.venue.trim() || null,
      matchAt: body.matchAt ? new Date(body.matchAt) : undefined,
      isHome: body.isHome,
      result: body.result === undefined ? undefined : body.result.trim() || null,
      sortOrder: body.sortOrder,
    },
  });
  return NextResponse.json(item);
}

export async function DELETE(_: Request, { params }: { params: Promise<{ id: string }> }) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  const { id } = await params;
  await prisma.baseMatch.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}

