import { NextResponse } from "next/server";
import crypto from "crypto";
import { prisma } from "@/lib/prisma";
import { getAdminUser } from "@/lib/auth";
import { sendMail } from "@/lib/mailer";
import { verificationEmailTemplate } from "@/lib/email-templates";

export async function POST(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const admin = await getAdminUser();
    if (!admin) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    const { id } = await params;

    const student = await prisma.students.findUnique({
      where: { id: Number(id) },
    });

    if (!student) {
      return NextResponse.json(
        { success: false, message: "Student not found" },
        { status: 404 }
      );
    }

    if (student.email_verified) {
      return NextResponse.json(
        { success: false, message: "This student's email is already verified." },
        { status: 400 }
      );
    }

    // ------------------------
    // Generate fresh verification token
    // ------------------------

    const verificationToken = crypto.randomBytes(32).toString("hex");
    const verificationExpiry = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24h

    await prisma.students.update({
      where: { id: student.id },
      data: {
        verification_token: verificationToken,
        verification_token_expiry: verificationExpiry,
      },
    });

    // ------------------------
    // Send verification email
    // ------------------------

    const verifyLink = `${process.env.NEXT_PUBLIC_APP_URL}/api/student/verify-email?token=${verificationToken}`;

    await sendMail({
      to: student.email,
      subject: "Verify your RKDA student account",
      html: verificationEmailTemplate(student.name, verifyLink),
    });

    return NextResponse.json({
      success: true,
      message: `Verification email resent to ${student.email}.`,
    });
  } catch (error) {
    console.error("Resend Verification Error:", error);
    return NextResponse.json(
      { success: false, message: "Failed to resend verification email." },
      { status: 500 }
    );
  }
}