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

export async function GET() {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  return NextResponse.json(
    await prisma.match.findMany({ orderBy: { matchAt: "desc" } })
  );
}

export async function POST(req: Request) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  const body = await req.json();
  const m = await prisma.match.create({
    data: {
      opponent: body.opponent,
      opponentLogoUrl: body.opponentLogoUrl ?? null,
      competition: body.competition ?? null,
      venue: body.venue ?? null,
      matchAt: new Date(body.matchAt),
      isHome: Boolean(body.isHome),
      result: body.result ?? null,
    },
  });
  return NextResponse.json(m);
}
