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) {
    await prisma.passwordResetToken.deleteMany({ where: { userId: user.id } });

    const token = randomUUID();
    const expiresAt = new Date(Date.now() + 60 * 60 * 1000);

    await prisma.passwordResetToken.create({
      data: {
        userId: user.id,
        token,
        expiresAt
      }
    });

    const baseUrl = process.env.NEXTAUTH_URL || "http://localhost:3000";
    const resetUrl = `${baseUrl}/reset/confirm?token=${token}`;

    await sendMail({
      to: email,
      subject: "Passwort zurücksetzen",
      text: `Passwort zurücksetzen: ${resetUrl}`
    });
  }

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