import { NextResponse } from "next/server";
import { prisma } from "../../../../lib/prisma";

export async function POST(request: Request) {
  const body = await request.json();
  const { token } = body || {};

  if (!token) {
    return NextResponse.json({ error: "Token erforderlich." }, { status: 400 });
  }

  const record = await prisma.verificationToken.findUnique({
    where: { token }
  });

  if (!record || record.expires < new Date()) {
    return NextResponse.json({ error: "Token ungültig." }, { status: 400 });
  }

  const user = await prisma.user.findUnique({
    where: { email: record.identifier }
  });

  if (!user) {
    return NextResponse.json({ error: "User nicht gefunden." }, { status: 404 });
  }

  await prisma.user.update({
    where: { id: user.id },
    data: { emailVerified: true }
  });

  await prisma.verificationToken.deleteMany({
    where: { identifier: record.identifier }
  });

  return NextResponse.json({ ok: true });
}
