import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";

export async function GET(req: NextRequest) {
  const user = await getCurrentUser(req);
  const participants = await prisma.participants.findMany({
    orderBy: { name: "asc" },
  });
  if (user) {
    return NextResponse.json(
      participants.map((p) => (p.id === user.id ? { ...p, name: "Me" } : p))
    );
  }
  return NextResponse.json(participants);
}

export async function POST(req: NextRequest) {
  const { name, email } = await req.json();
  if (!name?.trim()) {
    return NextResponse.json({ error: "name required" }, { status: 400 });
  }
  const participant = await prisma.participants.create({
    data: { name: name.trim(), email: email?.trim() || null },
  });
  return NextResponse.json(participant, { status: 201 });
}
