import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
import { prisma } from "@/lib/prisma";
import { sendMail } from "@/lib/mailer";
import { resetPasswordEmailTemplate } from "@/lib/email-templates";

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const email = body.email?.trim().toLowerCase();

    if (!email) {
      return NextResponse.json(
        { success: false, message: "Email is required." },
        { status: 400 }
      );
    }

    const student = await prisma.students.findUnique({ where: { email } });

    // Always respond with the same generic success message, whether or not the
    // email exists — this prevents leaking which emails are registered.
    const genericResponse = NextResponse.json({
      success: true,
      message: "If an account exists with that email, a reset link has been sent.",
    });

    if (!student) {
      return genericResponse;
    }

    const resetToken = crypto.randomBytes(32).toString("hex");
    const resetExpiry = new Date(Date.now() + 60 * 60 * 1000); // 1 hour

    await prisma.students.update({
      where: { id: student.id },
      data: {
        reset_token: resetToken,
        reset_token_expiry: resetExpiry,
      },
    });

    const resetLink = `${process.env.NEXT_PUBLIC_APP_URL}/student/reset-password?token=${resetToken}`;

    try {
      await sendMail({
        to: student.email,
        subject: "Reset your RKDA student password",
        html: resetPasswordEmailTemplate(student.name, resetLink),
      });
    } catch (mailErr) {
      console.error("Forgot Password Email Error:", mailErr);
      // still return generic success — don't reveal email send failures either
    }

    return genericResponse;
  } catch (error) {
    console.error("Forgot Password Error:", error);
    return NextResponse.json(
      { success: false, message: "Something went wrong." },
      { status: 500 }
    );
  }
}