import { randomUUID } from "crypto";
import { NextResponse } from "next/server";
import { prisma } from "../../../../lib/prisma";
import { sendMail } from "../../../../lib/mailer";

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

  if (!email) {
    return NextResponse.json({ error: "E-Mail erforderlich." }, { status: 400 });
  }

  const user = await prisma.user.findUnique({ where: { email } });
  if (!user) {
    return NextResponse.json({ ok: true });
  }

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

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

  const token = randomUUID();
  const expires = new Date(Date.now() + 24 * 60 * 60 * 1000);
  await prisma.verificationToken.create({
    data: {
      identifier: email,
      token,
      expires
    }
  });

  const baseUrl = process.env.NEXTAUTH_URL || "http://localhost:3000";
  const verifyUrl = `${baseUrl}/verify/confirm?token=${token}`;
  await sendMail({
    to: email,
    subject: "E-Mail verifizieren",
    text: `Bitte verifiziere deine E-Mail: ${verifyUrl}`
  });

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