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

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

    const { name, email, contact, password } = body;

    // ------------------------
    // Validation
    // ------------------------

    if (!name || name.trim() === "") {
      return NextResponse.json(
        { success: false, message: "Name is required." },
        { status: 400 }
      );
    }

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

    if (!contact || contact.trim() === "") {
      return NextResponse.json(
        { success: false, message: "Contact number is required." },
        { status: 400 }
      );
    }

    if (!password || password.trim() === "") {
      return NextResponse.json(
        { success: false, message: "Password is required." },
        { status: 400 }
      );
    }

    // ------------------------
    // Check email already exists
    // ------------------------

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

    if (emailExists) {
      return NextResponse.json(
        { success: false, message: "Email already registered." },
        { status: 400 }
      );
    }

    // ------------------------
    // Generate Student ID
    // ------------------------

    const PREFIX = "RKD"; // Change to "RKDA", "SL", etc. if needed

    const students = await prisma.students.findMany({
      where: {
        student_id: {
          startsWith: PREFIX,
        },
      },
      select: {
        student_id: true,
      },
    });

    let maxNumber = 100;

    for (const student of students) {
      const match = student.student_id.match(/^([A-Za-z]+)(\d+)$/);

      if (match) {
        maxNumber = Math.max(maxNumber, Number(match[2]));
      }
    }

    const studentId = `${PREFIX}${maxNumber + 1}`;

    // ------------------------
    // Hash password
    // ------------------------

    const hashedPassword = await bcrypt.hash(password, 10);

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

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

    // ------------------------
    // Create Student
    // ------------------------

    const student = await prisma.students.create({
      data: {
        student_id: studentId,
        name: name.trim(),
        email: email.trim().toLowerCase(),
        contact: contact.trim(),
        password: hashedPassword,
        email_verified: false,
        status: "inactive",
        verification_token: verificationToken,
        verification_token_expiry: verificationExpiry,
      },
    });

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

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

    try {
      await sendMail({
        to: student.email,
        subject: "Verify your RKDA student account",
        html: verificationEmailTemplate(student.name, verifyLink),
      });
    } catch (mailErr) {
      console.error("Verification Email Send Error:", mailErr);
      // Registration still succeeds even if email fails to send;
      // student can be re-sent verification later if you add that feature.
    }

    return NextResponse.json({
      success: true,
      message:
        "Registration successful. Please check your email to verify your account before logging in.",
      data: {
        id: student.id,
        student_id: student.student_id,
        name: student.name,
        email: student.email,
      },
    });
  } catch (error) {
    console.error("Student Register Error:", error);

    return NextResponse.json(
      { success: false, message: "Something went wrong." },
      { status: 500 }
    );
  }
}