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

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

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

  const resetToken = await prisma.passwordResetToken.findUnique({
    where: { token }
  });

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

  const passwordHash = await bcrypt.hash(newPassword, 10);

  await prisma.user.update({
    where: { id: resetToken.userId },
    data: { passwordHash }
  });

  await prisma.passwordResetToken.deleteMany({
    where: { userId: resetToken.userId }
  });

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